diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 808cc7e4..5b13107b 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -46,7 +46,7 @@ jobs: uses: ./.github/workflows/shared-build-and-deploy.yml with: ref: ${{ github.ref_name }} - server-id: central + server-id: skyflow-jfrog profile: jfrog tag: 'internal' module: ${{ needs.resolve-module.outputs.module }} diff --git a/common/pom.xml b/common/pom.xml index 72fff275..99f43063 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -21,4 +21,13 @@ 8 UTF-8 + + + + com.squareup.okhttp3 + mockwebserver + ${okhttp-version} + test + + \ No newline at end of file diff --git a/common/src/main/java/com/skyflow/BaseSkyflow.java b/common/src/main/java/com/skyflow/BaseSkyflow.java index d02dc45a..fdca3f26 100644 --- a/common/src/main/java/com/skyflow/BaseSkyflow.java +++ b/common/src/main/java/com/skyflow/BaseSkyflow.java @@ -4,7 +4,7 @@ import com.skyflow.config.Credentials; import com.skyflow.enums.LogLevel; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; @@ -66,7 +66,7 @@ public LogLevel getLogLevel() { } protected static T resolveOrThrow(Map map, String key, - ErrorLogs errorLog, ErrorMessage errorMessage) throws SkyflowException { + ErrorLogs errorLog, BaseErrorMessage errorMessage) throws SkyflowException { T value = key != null ? map.get(key) : map.values().stream().findFirst().orElse(null); if (value == null) { // The log line carries a %s1 placeholder for the id. Callers that resolve the single @@ -125,7 +125,7 @@ protected final void addVaultConfigTemplate(V vaultConfig) throws SkyflowExcepti ErrorLogs.VAULT_CONFIG_EXISTS.getLog(), vaultId )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - ErrorMessage.VaultIdAlreadyInConfigList.getMessage()); + BaseErrorMessage.VaultIdAlreadyInConfigList.getMessage()); } onVaultConfigAdded(vaultConfigCopy); this.vaultConfigMap.put(vaultId, vaultConfigCopy); @@ -139,7 +139,7 @@ protected final void updateVaultConfigTemplate(V vaultConfig) throws SkyflowExce LogUtil.printErrorLog(BaseUtils.parameterizedString( ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog(), vaultId )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.VaultIdNotInConfigList.getMessage()); } V previousConfig = this.vaultConfigMap.get(vaultId); V merged = mergeVaultConfig(vaultConfig, cloneVaultConfig(previousConfig)); @@ -150,7 +150,7 @@ protected final void updateVaultConfigTemplate(V vaultConfig) throws SkyflowExce protected final void removeVaultConfigTemplate(String vaultId) throws SkyflowException { if (!hasVaultClient(vaultId)) { LogUtil.printErrorLog(BaseUtils.parameterizedString(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog(), vaultId)); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.VaultIdNotInConfigList.getMessage()); } onVaultConfigRemoved(vaultId); this.vaultConfigMap.remove(vaultId); diff --git a/common/src/main/java/com/skyflow/BaseVaultClient.java b/common/src/main/java/com/skyflow/BaseVaultClient.java index 3d5b0d32..973510d7 100644 --- a/common/src/main/java/com/skyflow/BaseVaultClient.java +++ b/common/src/main/java/com/skyflow/BaseVaultClient.java @@ -5,7 +5,7 @@ import com.skyflow.config.BaseCredentials; import com.skyflow.config.BaseVaultConfig; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; @@ -25,7 +25,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Supplier; -class BaseVaultClient { +public class BaseVaultClient { protected V vaultConfig; protected OkHttpClient sharedHttpClient; protected String currentVaultURL; @@ -69,7 +69,7 @@ protected synchronized void prioritiseCredentials(BaseCredentials vaultSpecificC sysCredentials = dotenv.get(BaseConstants.ENV_CREDENTIALS_KEY_NAME); } if (sysCredentials == null) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentials.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyCredentials.getMessage()); } else { this.finalCredentials = new BaseCredentials(); this.finalCredentials.setCredentialsString(sysCredentials); @@ -80,7 +80,7 @@ protected synchronized void prioritiseCredentials(BaseCredentials vaultSpecificC apiKey = null; } } catch (DotenvException e) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentials.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyCredentials.getMessage()); } catch (SkyflowException e) { throw e; } catch (Exception e) { diff --git a/common/src/main/java/com/skyflow/detect/Audio.java b/common/src/main/java/com/skyflow/detect/Audio.java new file mode 100644 index 00000000..6d4e46f9 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Audio.java @@ -0,0 +1,93 @@ +package com.skyflow.detect; + +/** + * Audio processing options. + */ +public final class Audio { + private final Boolean outputProcessedAudio; + private final OutputTranscriptionType outputTranscription; + private final Bleep bleep; + + private Audio(AudioBuilder builder) { + this.outputProcessedAudio = builder.outputProcessedAudio; + this.outputTranscription = builder.outputTranscription; + this.bleep = builder.bleep; + } + + /** + * @return a new builder + */ + public static AudioBuilder builder() { + return new AudioBuilder(); + } + + /** + * @return Whether to return the processed audio file. + */ + public Boolean getOutputProcessedAudio() { + return outputProcessedAudio; + } + + /** + * @return Transcription output to produce. + */ + public OutputTranscriptionType getOutputTranscription() { + return outputTranscription; + } + + /** + * @return Bleep configuration. + */ + public Bleep getBleep() { + return bleep; + } + + @Override + public String toString() { + return "Audio{" + + "outputProcessedAudio=" + outputProcessedAudio + + ", outputTranscription=" + outputTranscription + + ", bleep=" + bleep + + '}'; + } + + public static final class AudioBuilder { + private Boolean outputProcessedAudio; + private OutputTranscriptionType outputTranscription; + private Bleep bleep; + + private AudioBuilder() { + } + + /** + * @param outputProcessedAudio Whether to return the processed audio file. + * @return this builder + */ + public AudioBuilder outputProcessedAudio(Boolean outputProcessedAudio) { + this.outputProcessedAudio = outputProcessedAudio; + return this; + } + + /** + * @param outputTranscription Transcription output to produce. + * @return this builder + */ + public AudioBuilder outputTranscription(OutputTranscriptionType outputTranscription) { + this.outputTranscription = outputTranscription; + return this; + } + + /** + * @param bleep Bleep configuration. + * @return this builder + */ + public AudioBuilder bleep(Bleep bleep) { + this.bleep = bleep; + return this; + } + + public Audio build() { + return new Audio(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/Bleep.java b/common/src/main/java/com/skyflow/detect/Bleep.java new file mode 100644 index 00000000..63346aeb --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Bleep.java @@ -0,0 +1,113 @@ +package com.skyflow.detect; + +/** + * Bleep tone applied over detected speech in audio. + */ +public final class Bleep { + private final Float startPadding; + private final Float stopPadding; + private final Integer frequency; + private final Integer gain; + + private Bleep(BleepBuilder builder) { + this.startPadding = builder.startPadding; + this.stopPadding = builder.stopPadding; + this.frequency = builder.frequency; + this.gain = builder.gain; + } + + /** + * @return a new builder + */ + public static BleepBuilder builder() { + return new BleepBuilder(); + } + + /** + * @return Seconds of bleep added before the detected span. + */ + public Float getStartPadding() { + return startPadding; + } + + /** + * @return Seconds of bleep added after the detected span. + */ + public Float getStopPadding() { + return stopPadding; + } + + /** + * @return Bleep frequency in Hz. + */ + public Integer getFrequency() { + return frequency; + } + + /** + * @return Bleep gain. + */ + public Integer getGain() { + return gain; + } + + @Override + public String toString() { + return "Bleep{" + + "startPadding=" + startPadding + + ", stopPadding=" + stopPadding + + ", frequency=" + frequency + + ", gain=" + gain + + '}'; + } + + public static final class BleepBuilder { + private Float startPadding; + private Float stopPadding; + private Integer frequency; + private Integer gain; + + private BleepBuilder() { + } + + /** + * @param startPadding Seconds of bleep added before the detected span. + * @return this builder + */ + public BleepBuilder startPadding(Float startPadding) { + this.startPadding = startPadding; + return this; + } + + /** + * @param stopPadding Seconds of bleep added after the detected span. + * @return this builder + */ + public BleepBuilder stopPadding(Float stopPadding) { + this.stopPadding = stopPadding; + return this; + } + + /** + * @param frequency Bleep frequency in Hz. + * @return this builder + */ + public BleepBuilder frequency(Integer frequency) { + this.frequency = frequency; + return this; + } + + /** + * @param gain Bleep gain. + * @return this builder + */ + public BleepBuilder gain(Integer gain) { + this.gain = gain; + return this; + } + + public Bleep build() { + return new Bleep(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/CheckGuardrailsRequest.java b/common/src/main/java/com/skyflow/detect/CheckGuardrailsRequest.java new file mode 100644 index 00000000..526ddd9c --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/CheckGuardrailsRequest.java @@ -0,0 +1,95 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * Request for {@code checkGuardrails}: screens text for toxicity and denied topics. + */ +public final class CheckGuardrailsRequest { + private final String text; + private final Boolean checkToxicity; + private final List denyTopics; + + private CheckGuardrailsRequest(CheckGuardrailsRequestBuilder builder) { + this.text = builder.text; + this.checkToxicity = builder.checkToxicity; + this.denyTopics = builder.denyTopics; + } + + /** + * @return a new builder + */ + public static CheckGuardrailsRequestBuilder builder() { + return new CheckGuardrailsRequestBuilder(); + } + + /** + * @return Text to screen. Required. + */ + public String getText() { + return text; + } + + /** + * @return Whether to check the text for toxicity. + */ + public Boolean getCheckToxicity() { + return checkToxicity; + } + + /** + * @return Topics the text must not discuss. + */ + public List getDenyTopics() { + return denyTopics; + } + + @Override + public String toString() { + return "CheckGuardrailsRequest{" + + "text=" + text + + ", checkToxicity=" + checkToxicity + + ", denyTopics=" + denyTopics + + '}'; + } + + public static final class CheckGuardrailsRequestBuilder { + private String text; + private Boolean checkToxicity; + private List denyTopics; + + private CheckGuardrailsRequestBuilder() { + } + + /** + * @param text Text to screen. Required. + * @return this builder + */ + public CheckGuardrailsRequestBuilder text(String text) { + this.text = text; + return this; + } + + /** + * @param checkToxicity Whether to check the text for toxicity. + * @return this builder + */ + public CheckGuardrailsRequestBuilder checkToxicity(Boolean checkToxicity) { + this.checkToxicity = checkToxicity; + return this; + } + + /** + * @param denyTopics Topics the text must not discuss. + * @return this builder + */ + public CheckGuardrailsRequestBuilder denyTopics(List denyTopics) { + this.denyTopics = denyTopics; + return this; + } + + public CheckGuardrailsRequest build() { + return new CheckGuardrailsRequest(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/CheckGuardrailsResponse.java b/common/src/main/java/com/skyflow/detect/CheckGuardrailsResponse.java new file mode 100644 index 00000000..153e68cf --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/CheckGuardrailsResponse.java @@ -0,0 +1,56 @@ +package com.skyflow.detect; + +/** + * Response of {@code checkGuardrails}. + */ +public final class CheckGuardrailsResponse { + private final String text; + private final GuardrailsValidation validation; + private final Boolean toxic; + private final Boolean deniedTopic; + + public CheckGuardrailsResponse(String text, GuardrailsValidation validation, Boolean toxic, Boolean deniedTopic) { + this.text = text; + this.validation = validation; + this.toxic = toxic; + this.deniedTopic = deniedTopic; + } + + /** + * @return The text that was screened. + */ + public String getText() { + return text; + } + + /** + * @return PASSED when no guardrail was triggered, FAILED otherwise. + */ + public GuardrailsValidation getValidation() { + return validation; + } + + /** + * @return Whether the text was judged toxic. Null when toxicity was not checked. + */ + public Boolean getToxic() { + return toxic; + } + + /** + * @return Whether the text touched a denied topic. Null when no topics were supplied. + */ + public Boolean getDeniedTopic() { + return deniedTopic; + } + + @Override + public String toString() { + return "CheckGuardrailsResponse{" + + "text=" + text + + ", validation=" + validation + + ", toxic=" + toxic + + ", deniedTopic=" + deniedTopic + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/CustomType.java b/common/src/main/java/com/skyflow/detect/CustomType.java new file mode 100644 index 00000000..1eee269a --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/CustomType.java @@ -0,0 +1,75 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * A custom, regex-defined entity type. + */ +public final class CustomType { + private final String label; + private final List match; + + private CustomType(CustomTypeBuilder builder) { + this.label = builder.label; + this.match = builder.match; + } + + /** + * @return a new builder + */ + public static CustomTypeBuilder builder() { + return new CustomTypeBuilder(); + } + + /** + * @return Label reported as the entityType of matches. + */ + public String getLabel() { + return label; + } + + /** + * @return Regular expressions that identify the custom entity. + */ + public List getMatch() { + return match; + } + + @Override + public String toString() { + return "CustomType{" + + "label=" + label + + ", match=" + match + + '}'; + } + + public static final class CustomTypeBuilder { + private String label; + private List match; + + private CustomTypeBuilder() { + } + + /** + * @param label Label reported as the entityType of matches. + * @return this builder + */ + public CustomTypeBuilder label(String label) { + this.label = label; + return this; + } + + /** + * @param match Regular expressions that identify the custom entity. + * @return this builder + */ + public CustomTypeBuilder match(List match) { + this.match = match; + return this; + } + + public CustomType build() { + return new CustomType(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/DataSourceType.java b/common/src/main/java/com/skyflow/detect/DataSourceType.java new file mode 100644 index 00000000..d152fbb4 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DataSourceType.java @@ -0,0 +1,10 @@ +package com.skyflow.detect; + +/** + * How file content is supplied to, or returned by, Detect file operations. + */ +public enum DataSourceType { + BASE64, + SKYFLOW_ID, + PRESIGNED_URL; +} diff --git a/common/src/main/java/com/skyflow/detect/DeidentificationType.java b/common/src/main/java/com/skyflow/detect/DeidentificationType.java new file mode 100644 index 00000000..067d533f --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DeidentificationType.java @@ -0,0 +1,12 @@ +package com.skyflow.detect; + +/** + * How a detected entity is replaced in the processed output. + */ +public enum DeidentificationType { + UNKNOWN, + ENTITY_UNIQUE_COUNTER, + ENTITY_ONLY, + VAULT_TOKEN, + MASK; +} diff --git a/common/src/main/java/com/skyflow/detect/DeidentifyFileRequest.java b/common/src/main/java/com/skyflow/detect/DeidentifyFileRequest.java new file mode 100644 index 00000000..b91b3a76 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DeidentifyFileRequest.java @@ -0,0 +1,212 @@ +package com.skyflow.detect; + +import java.io.File; + +/** + * Request for {@code deidentifyFile}. Supply the file through exactly one of {@code value} (with a + * {@code dataSource}), {@code file} or {@code filePath}. The two file forms are builder sugar that set + * {@code dataSource = BASE64}, encode the content into {@code value} when the request is sent, and infer + * {@code dataFormat} from the extension unless it is set explicitly. + * + *

Without {@code pollOptions} the call submits the run and returns its id. With {@code pollOptions} the + * SDK polls the run and, on success for a file-based request, writes the outputs to disk. + */ +public final class DeidentifyFileRequest { + private final DataSourceType dataSource; + private final String value; + private final File file; + private final FileDataFormat dataFormat; + private final String configurationId; + private final DetectConfiguration configuration; + private final PollOptions pollOptions; + private final String outputDirectory; + + private DeidentifyFileRequest(DeidentifyFileRequestBuilder builder) { + this.dataSource = builder.dataSource; + this.value = builder.value; + this.file = builder.file; + this.dataFormat = builder.dataFormat; + this.configurationId = builder.configurationId; + this.configuration = builder.configuration; + this.pollOptions = builder.pollOptions; + this.outputDirectory = builder.outputDirectory; + } + + /** + * @return a new builder + */ + public static DeidentifyFileRequestBuilder builder() { + return new DeidentifyFileRequestBuilder(); + } + + /** + * @return How {@code value} supplies the file. Required unless {@code file} or {@code filePath} was used. + */ + public DataSourceType getDataSource() { + return dataSource; + } + + /** + * @return Base64 content, skyflow id or presigned URL, according to {@code dataSource}. + */ + public String getValue() { + return value; + } + + /** + * @return Local file to de-identify, when {@code file} or {@code filePath} was used. + */ + public File getFile() { + return file; + } + + /** + * @return Format of the file. Optional; inferred from the file extension or by the server when omitted. + */ + public FileDataFormat getDataFormat() { + return dataFormat; + } + + /** + * @return Id of a stored Detect configuration. + */ + public String getConfigurationId() { + return configurationId; + } + + /** + * @return Inline Detect configuration. + */ + public DetectConfiguration getConfiguration() { + return configuration; + } + + /** + * @return Polling settings, or null to submit only. + */ + public PollOptions getPollOptions() { + return pollOptions; + } + + /** + * @return Directory the outputs are written to on success. Only with {@code pollOptions} and a file-based request. + */ + public String getOutputDirectory() { + return outputDirectory; + } + + @Override + public String toString() { + return "DeidentifyFileRequest{" + + "dataSource=" + dataSource + + ", value=" + (value == null ? null : "<" + value.length() + " chars>") + + ", file=" + file + + ", dataFormat=" + dataFormat + + ", configurationId=" + configurationId + + ", configuration=" + configuration + + ", pollOptions=" + pollOptions + + ", outputDirectory=" + outputDirectory + + '}'; + } + + public static final class DeidentifyFileRequestBuilder { + private DataSourceType dataSource; + private String value; + private File file; + private FileDataFormat dataFormat; + private String configurationId; + private DetectConfiguration configuration; + private PollOptions pollOptions; + private String outputDirectory; + + private DeidentifyFileRequestBuilder() { + } + + /** + * @param dataSource How {@code value} supplies the file. + * @return this builder + */ + public DeidentifyFileRequestBuilder dataSource(DataSourceType dataSource) { + this.dataSource = dataSource; + return this; + } + + /** + * @param value Base64 content, skyflow id or presigned URL, according to {@code dataSource}. + * @return this builder + */ + public DeidentifyFileRequestBuilder value(String value) { + this.value = value; + return this; + } + + /** + * @param file Local file to de-identify. Sets {@code dataSource} to BASE64; the content is encoded when sent. + * @return this builder + */ + public DeidentifyFileRequestBuilder file(File file) { + this.file = file; + if (file != null) { + this.dataSource = DataSourceType.BASE64; + } + return this; + } + + /** + * @param filePath Path of a local file to de-identify. Same as {@link #file(File)}. + * @return this builder + */ + public DeidentifyFileRequestBuilder filePath(String filePath) { + return file(filePath == null ? null : new File(filePath)); + } + + /** + * @param dataFormat Format of the file. Optional. + * @return this builder + */ + public DeidentifyFileRequestBuilder dataFormat(FileDataFormat dataFormat) { + this.dataFormat = dataFormat; + return this; + } + + /** + * @param configurationId Id of a stored Detect configuration. + * @return this builder + */ + public DeidentifyFileRequestBuilder configurationId(String configurationId) { + this.configurationId = configurationId; + return this; + } + + /** + * @param configuration Inline Detect configuration. + * @return this builder + */ + public DeidentifyFileRequestBuilder configuration(DetectConfiguration configuration) { + this.configuration = configuration; + return this; + } + + /** + * @param pollOptions Poll the run after submitting. Null to submit only. + * @return this builder + */ + public DeidentifyFileRequestBuilder pollOptions(PollOptions pollOptions) { + this.pollOptions = pollOptions; + return this; + } + + /** + * @param outputDirectory Where to write outputs on success. Requires {@code pollOptions} and a file-based request. + * @return this builder + */ + public DeidentifyFileRequestBuilder outputDirectory(String outputDirectory) { + this.outputDirectory = outputDirectory; + return this; + } + + public DeidentifyFileRequest build() { + return new DeidentifyFileRequest(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/DeidentifyFileResponse.java b/common/src/main/java/com/skyflow/detect/DeidentifyFileResponse.java new file mode 100644 index 00000000..482b3b63 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DeidentifyFileResponse.java @@ -0,0 +1,83 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * Response of {@code deidentifyFile}. {@code runId} is always present. {@code status} is null when the + * request did not poll; retrieve the run later with {@code getRun}. When polled, the remaining fields + * mirror {@link GetRunResponse}: output, outputType and metrics are populated only on SUCCESS, and + * message carries the failure detail on FAILED. + */ +public final class DeidentifyFileResponse { + private final String runId; + private final DetectRunStatus status; + private final DataSourceType outputType; + private final List output; + private final Metrics metrics; + private final String message; + + public DeidentifyFileResponse(String runId, DetectRunStatus status, DataSourceType outputType, + List output, Metrics metrics, String message) { + this.runId = runId; + this.status = status; + this.outputType = outputType; + this.output = output; + this.metrics = metrics; + this.message = message; + } + + /** + * @return Run id returned by the submit call. Use it with {@code getRun} to retrieve or resume. + */ + public String getRunId() { + return runId; + } + + /** + * @return Run status after polling. Null when the request did not poll. IN_PROGRESS or QUEUED when the + * polling budget ran out before the run finished. + */ + public DetectRunStatus getStatus() { + return status; + } + + /** + * @return How output files are delivered. Null unless polled to SUCCESS. + */ + public DataSourceType getOutputType() { + return outputType; + } + + /** + * @return Output artifacts. Empty unless polled to SUCCESS, never null. + */ + public List getOutput() { + return output; + } + + /** + * @return Processing metrics. Null unless polled to SUCCESS. + */ + public Metrics getMetrics() { + return metrics; + } + + /** + * @return Failure detail when status is FAILED. + */ + public String getMessage() { + return message; + } + + @Override + public String toString() { + return "DeidentifyFileResponse{" + + "runId=" + runId + + ", status=" + status + + ", outputType=" + outputType + + ", output=" + output + + ", metrics=" + metrics + + ", message=" + message + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/DeidentifyStringRequest.java b/common/src/main/java/com/skyflow/detect/DeidentifyStringRequest.java new file mode 100644 index 00000000..bde84343 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DeidentifyStringRequest.java @@ -0,0 +1,94 @@ +package com.skyflow.detect; + +/** + * Request for {@code deidentifyString}. configurationId and configuration are both optional and are sent + * exactly as supplied; the server applies its own rules for their combination. + */ +public final class DeidentifyStringRequest { + private final String text; + private final String configurationId; + private final DetectConfiguration configuration; + + private DeidentifyStringRequest(DeidentifyStringRequestBuilder builder) { + this.text = builder.text; + this.configurationId = builder.configurationId; + this.configuration = builder.configuration; + } + + /** + * @return a new builder + */ + public static DeidentifyStringRequestBuilder builder() { + return new DeidentifyStringRequestBuilder(); + } + + /** + * @return Text to de-identify. Required. + */ + public String getText() { + return text; + } + + /** + * @return Id of a stored Detect configuration. + */ + public String getConfigurationId() { + return configurationId; + } + + /** + * @return Inline Detect configuration. + */ + public DetectConfiguration getConfiguration() { + return configuration; + } + + @Override + public String toString() { + return "DeidentifyStringRequest{" + + "text=" + text + + ", configurationId=" + configurationId + + ", configuration=" + configuration + + '}'; + } + + public static final class DeidentifyStringRequestBuilder { + private String text; + private String configurationId; + private DetectConfiguration configuration; + + private DeidentifyStringRequestBuilder() { + } + + /** + * @param text Text to de-identify. Required. + * @return this builder + */ + public DeidentifyStringRequestBuilder text(String text) { + this.text = text; + return this; + } + + /** + * @param configurationId Id of a stored Detect configuration. + * @return this builder + */ + public DeidentifyStringRequestBuilder configurationId(String configurationId) { + this.configurationId = configurationId; + return this; + } + + /** + * @param configuration Inline Detect configuration. + * @return this builder + */ + public DeidentifyStringRequestBuilder configuration(DetectConfiguration configuration) { + this.configuration = configuration; + return this; + } + + public DeidentifyStringRequest build() { + return new DeidentifyStringRequest(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/DeidentifyStringResponse.java b/common/src/main/java/com/skyflow/detect/DeidentifyStringResponse.java new file mode 100644 index 00000000..7ea68dcf --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DeidentifyStringResponse.java @@ -0,0 +1,48 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * Response of {@code deidentifyString}. + */ +public final class DeidentifyStringResponse { + private final String processedText; + private final List entities; + private final Metrics metrics; + + public DeidentifyStringResponse(String processedText, List entities, Metrics metrics) { + this.processedText = processedText; + this.entities = entities; + this.metrics = metrics; + } + + /** + * @return De-identified text. + */ + public String getProcessedText() { + return processedText; + } + + /** + * @return Detected entities. Never null. + */ + public List getEntities() { + return entities; + } + + /** + * @return Processing metrics. + */ + public Metrics getMetrics() { + return metrics; + } + + @Override + public String toString() { + return "DeidentifyStringResponse{" + + "processedText=" + processedText + + ", entities=" + entities + + ", metrics=" + metrics + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/Detect.java b/common/src/main/java/com/skyflow/detect/Detect.java new file mode 100644 index 00000000..dc998e57 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Detect.java @@ -0,0 +1,155 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * Detection policy: which entities to look for and how to replace them. + */ +public final class Detect { + private final List entities; + private final List objectEntities; + private final List restrict; + private final List skip; + private final List customTypes; + private final ReturnEntitiesType returnEntities; + + private Detect(DetectBuilder builder) { + this.entities = builder.entities; + this.objectEntities = builder.objectEntities; + this.restrict = builder.restrict; + this.skip = builder.skip; + this.customTypes = builder.customTypes; + this.returnEntities = builder.returnEntities; + } + + /** + * @return a new builder + */ + public static DetectBuilder builder() { + return new DetectBuilder(); + } + + /** + * @return Per-entity rules. + */ + public List getEntities() { + return entities; + } + + /** + * @return Per-object rules. File inputs only. + */ + public List getObjectEntities() { + return objectEntities; + } + + /** + * @return Regular expressions that are always treated as sensitive. + */ + public List getRestrict() { + return restrict; + } + + /** + * @return Regular expressions that are never treated as sensitive. + */ + public List getSkip() { + return skip; + } + + /** + * @return Custom regex-defined entity types. + */ + public List getCustomTypes() { + return customTypes; + } + + /** + * @return Which entities to return. Defaults to EXCLUDE_SENSITIVE_DATA on the server. + */ + public ReturnEntitiesType getReturnEntities() { + return returnEntities; + } + + @Override + public String toString() { + return "Detect{" + + "entities=" + entities + + ", objectEntities=" + objectEntities + + ", restrict=" + restrict + + ", skip=" + skip + + ", customTypes=" + customTypes + + ", returnEntities=" + returnEntities + + '}'; + } + + public static final class DetectBuilder { + private List entities; + private List objectEntities; + private List restrict; + private List skip; + private List customTypes; + private ReturnEntitiesType returnEntities; + + private DetectBuilder() { + } + + /** + * @param entities Per-entity rules. + * @return this builder + */ + public DetectBuilder entities(List entities) { + this.entities = entities; + return this; + } + + /** + * @param objectEntities Per-object rules. File inputs only. + * @return this builder + */ + public DetectBuilder objectEntities(List objectEntities) { + this.objectEntities = objectEntities; + return this; + } + + /** + * @param restrict Regular expressions that are always treated as sensitive. + * @return this builder + */ + public DetectBuilder restrict(List restrict) { + this.restrict = restrict; + return this; + } + + /** + * @param skip Regular expressions that are never treated as sensitive. + * @return this builder + */ + public DetectBuilder skip(List skip) { + this.skip = skip; + return this; + } + + /** + * @param customTypes Custom regex-defined entity types. + * @return this builder + */ + public DetectBuilder customTypes(List customTypes) { + this.customTypes = customTypes; + return this; + } + + /** + * @param returnEntities Which entities to return. Defaults to EXCLUDE_SENSITIVE_DATA on the server. + * @return this builder + */ + public DetectBuilder returnEntities(ReturnEntitiesType returnEntities) { + this.returnEntities = returnEntities; + return this; + } + + public Detect build() { + return new Detect(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/DetectConfiguration.java b/common/src/main/java/com/skyflow/detect/DetectConfiguration.java new file mode 100644 index 00000000..e9209528 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DetectConfiguration.java @@ -0,0 +1,135 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * An inline Detect configuration, used instead of a stored configuration id. + */ +public final class DetectConfiguration { + private final String name; + private final String description; + private final Detect detect; + private final List fileMapping; + private final Media media; + + private DetectConfiguration(DetectConfigurationBuilder builder) { + this.name = builder.name; + this.description = builder.description; + this.detect = builder.detect; + this.fileMapping = builder.fileMapping; + this.media = builder.media; + } + + /** + * @return a new builder + */ + public static DetectConfigurationBuilder builder() { + return new DetectConfigurationBuilder(); + } + + /** + * @return Configuration name. + */ + public String getName() { + return name; + } + + /** + * @return Configuration description. + */ + public String getDescription() { + return description; + } + + /** + * @return Detection policy. + */ + public Detect getDetect() { + return detect; + } + + /** + * @return File mappings. File inputs only. + */ + public List getFileMapping() { + return fileMapping; + } + + /** + * @return Media options. File inputs only. + */ + public Media getMedia() { + return media; + } + + @Override + public String toString() { + return "DetectConfiguration{" + + "name=" + name + + ", description=" + description + + ", detect=" + detect + + ", fileMapping=" + fileMapping + + ", media=" + media + + '}'; + } + + public static final class DetectConfigurationBuilder { + private String name; + private String description; + private Detect detect; + private List fileMapping; + private Media media; + + private DetectConfigurationBuilder() { + } + + /** + * @param name Configuration name. + * @return this builder + */ + public DetectConfigurationBuilder name(String name) { + this.name = name; + return this; + } + + /** + * @param description Configuration description. + * @return this builder + */ + public DetectConfigurationBuilder description(String description) { + this.description = description; + return this; + } + + /** + * @param detect Detection policy. + * @return this builder + */ + public DetectConfigurationBuilder detect(Detect detect) { + this.detect = detect; + return this; + } + + /** + * @param fileMapping File mappings. File inputs only. + * @return this builder + */ + public DetectConfigurationBuilder fileMapping(List fileMapping) { + this.fileMapping = fileMapping; + return this; + } + + /** + * @param media Media options. File inputs only. + * @return this builder + */ + public DetectConfigurationBuilder media(Media media) { + this.media = media; + return this; + } + + public DetectConfiguration build() { + return new DetectConfiguration(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/DetectRunStatus.java b/common/src/main/java/com/skyflow/detect/DetectRunStatus.java new file mode 100644 index 00000000..3bb05886 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DetectRunStatus.java @@ -0,0 +1,12 @@ +package com.skyflow.detect; + +/** + * Lifecycle status of an asynchronous Detect file run. + */ +public enum DetectRunStatus { + UNKNOWN, + QUEUED, + IN_PROGRESS, + SUCCESS, + FAILED; +} diff --git a/common/src/main/java/com/skyflow/detect/DetectedEntity.java b/common/src/main/java/com/skyflow/detect/DetectedEntity.java new file mode 100644 index 00000000..6a443d1c --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/DetectedEntity.java @@ -0,0 +1,68 @@ +package com.skyflow.detect; + +import java.util.Map; + +/** + * An entity detected in the input text. + */ +public final class DetectedEntity { + private final String token; + private final String value; + private final EntityLocation location; + private final String entityType; + private final Map entityScores; + + public DetectedEntity(String token, String value, EntityLocation location, String entityType, Map entityScores) { + this.token = token; + this.value = value; + this.location = location; + this.entityType = entityType; + this.entityScores = entityScores; + } + + /** + * @return Replacement token, for example NAME_1. + */ + public String getToken() { + return token; + } + + /** + * @return Original value. Empty unless returnEntities is ALL. + */ + public String getValue() { + return value; + } + + /** + * @return Where the entity was found. + */ + public EntityLocation getLocation() { + return location; + } + + /** + * @return Entity type. Carries custom-type labels as well as built-in types. + */ + public String getEntityType() { + return entityType; + } + + /** + * @return Confidence scores by entity type, 0.0 to 1.0. + */ + public Map getEntityScores() { + return entityScores; + } + + @Override + public String toString() { + return "DetectedEntity{" + + "token=" + token + + ", value=" + value + + ", location=" + location + + ", entityType=" + entityType + + ", entityScores=" + entityScores + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/Document.java b/common/src/main/java/com/skyflow/detect/Document.java new file mode 100644 index 00000000..2d461196 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Document.java @@ -0,0 +1,53 @@ +package com.skyflow.detect; + +/** + * Document processing options. + */ +public final class Document { + private final Pdf pdf; + + private Document(DocumentBuilder builder) { + this.pdf = builder.pdf; + } + + /** + * @return a new builder + */ + public static DocumentBuilder builder() { + return new DocumentBuilder(); + } + + /** + * @return PDF options. + */ + public Pdf getPdf() { + return pdf; + } + + @Override + public String toString() { + return "Document{" + + "pdf=" + pdf + + '}'; + } + + public static final class DocumentBuilder { + private Pdf pdf; + + private DocumentBuilder() { + } + + /** + * @param pdf PDF options. + * @return this builder + */ + public DocumentBuilder pdf(Pdf pdf) { + this.pdf = pdf; + return this; + } + + public Document build() { + return new Document(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/Entity.java b/common/src/main/java/com/skyflow/detect/Entity.java new file mode 100644 index 00000000..992acafd --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Entity.java @@ -0,0 +1,113 @@ +package com.skyflow.detect; + +/** + * Configures how a single entity type is detected and de-identified. + */ +public final class Entity { + private final EntityType entityType; + private final DeidentificationType deidentificationType; + private final String destination; + private final Transformation transformation; + + private Entity(EntityBuilder builder) { + this.entityType = builder.entityType; + this.deidentificationType = builder.deidentificationType; + this.destination = builder.destination; + this.transformation = builder.transformation; + } + + /** + * @return a new builder + */ + public static EntityBuilder builder() { + return new EntityBuilder(); + } + + /** + * @return Entity type this rule applies to. Defaults to ALL on the server. + */ + public EntityType getEntityType() { + return entityType; + } + + /** + * @return Replacement strategy. Defaults to ENTITY_UNIQUE_COUNTER on the server. + */ + public DeidentificationType getDeidentificationType() { + return deidentificationType; + } + + /** + * @return Where vault tokens are stored: a table.column (skyvault) or token-group name (flowvault). Only used with VAULT_TOKEN. + */ + public String getDestination() { + return destination; + } + + /** + * @return Optional transformation applied to the detected value. + */ + public Transformation getTransformation() { + return transformation; + } + + @Override + public String toString() { + return "Entity{" + + "entityType=" + entityType + + ", deidentificationType=" + deidentificationType + + ", destination=" + destination + + ", transformation=" + transformation + + '}'; + } + + public static final class EntityBuilder { + private EntityType entityType; + private DeidentificationType deidentificationType; + private String destination; + private Transformation transformation; + + private EntityBuilder() { + } + + /** + * @param entityType Entity type this rule applies to. Defaults to ALL on the server. + * @return this builder + */ + public EntityBuilder entityType(EntityType entityType) { + this.entityType = entityType; + return this; + } + + /** + * @param deidentificationType Replacement strategy. Defaults to ENTITY_UNIQUE_COUNTER on the server. + * @return this builder + */ + public EntityBuilder deidentificationType(DeidentificationType deidentificationType) { + this.deidentificationType = deidentificationType; + return this; + } + + /** + * @param destination Where vault tokens are stored: a table.column (skyvault) or token-group name (flowvault). Only used with VAULT_TOKEN. + * @return this builder + */ + public EntityBuilder destination(String destination) { + this.destination = destination; + return this; + } + + /** + * @param transformation Optional transformation applied to the detected value. + * @return this builder + */ + public EntityBuilder transformation(Transformation transformation) { + this.transformation = transformation; + return this; + } + + public Entity build() { + return new Entity(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/EntityLocation.java b/common/src/main/java/com/skyflow/detect/EntityLocation.java new file mode 100644 index 00000000..88b45048 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/EntityLocation.java @@ -0,0 +1,56 @@ +package com.skyflow.detect; + +/** + * Position of a detected entity in the original and processed text. + */ +public final class EntityLocation { + private final Integer startIndex; + private final Integer endIndex; + private final Integer startIndexProcessed; + private final Integer endIndexProcessed; + + public EntityLocation(Integer startIndex, Integer endIndex, Integer startIndexProcessed, Integer endIndexProcessed) { + this.startIndex = startIndex; + this.endIndex = endIndex; + this.startIndexProcessed = startIndexProcessed; + this.endIndexProcessed = endIndexProcessed; + } + + /** + * @return Start index in the original text. + */ + public Integer getStartIndex() { + return startIndex; + } + + /** + * @return End index in the original text. + */ + public Integer getEndIndex() { + return endIndex; + } + + /** + * @return Start index in the processed text. + */ + public Integer getStartIndexProcessed() { + return startIndexProcessed; + } + + /** + * @return End index in the processed text. + */ + public Integer getEndIndexProcessed() { + return endIndexProcessed; + } + + @Override + public String toString() { + return "EntityLocation{" + + "startIndex=" + startIndex + + ", endIndex=" + endIndex + + ", startIndexProcessed=" + startIndexProcessed + + ", endIndexProcessed=" + endIndexProcessed + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/EntityType.java b/common/src/main/java/com/skyflow/detect/EntityType.java new file mode 100644 index 00000000..99cbbd8a --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/EntityType.java @@ -0,0 +1,78 @@ +package com.skyflow.detect; + +/** + * Entity types Skyflow Detect can identify. Also used to target entities in {@link RedactionLevel}. + */ +public enum EntityType { + NONE, + ACCOUNT_NUMBER, + AGE, + ALL, + BANK_ACCOUNT, + BLOOD_TYPE, + CONDITION, + CORPORATE_ACTION, + CREDIT_CARD, + CREDIT_CARD_EXPIRATION, + CVV, + DATE, + DATE_INTERVAL, + DAY, + DOB, + DOSE, + DRIVER_LICENSE, + DRUG, + DURATION, + EFFECT, + EMAIL_ADDRESS, + EVENT, + FILENAME, + FINANCIAL_METRIC, + GENDER, + HEALTHCARE_NUMBER, + INJURY, + IP_ADDRESS, + LANGUAGE, + LOCATION, + LOCATION_ADDRESS, + LOCATION_ADDRESS_STREET, + LOCATION_CITY, + LOCATION_COORDINATE, + LOCATION_COUNTRY, + LOCATION_STATE, + LOCATION_ZIP, + MARITAL_STATUS, + MEDICAL_CODE, + MEDICAL_PROCESS, + MONEY, + MONTH, + NAME, + NAME_FAMILY, + NAME_GIVEN, + NAME_MEDICAL_PROFESSIONAL, + NUMERICAL_PII, + OCCUPATION, + ORGANIZATION, + ORGANIZATION_ID, + ORGANIZATION_MEDICAL_FACILITY, + ORIGIN, + PASSPORT_NUMBER, + PASSWORD, + PHONE_NUMBER, + PHYSICAL_ATTRIBUTE, + POLITICAL_AFFILIATION, + PRODUCT, + PROJECT, + RELIGION, + ROUTING_NUMBER, + SEXUALITY, + SSN, + STATISTICS, + TIME, + TREND, + URL, + USERNAME, + VEHICLE_ID, + YEAR, + ZODIAC_SIGN; +} diff --git a/common/src/main/java/com/skyflow/detect/FileDataFormat.java b/common/src/main/java/com/skyflow/detect/FileDataFormat.java new file mode 100644 index 00000000..047cb54b --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/FileDataFormat.java @@ -0,0 +1,30 @@ +package com.skyflow.detect; + +/** + * File formats understood by Detect file operations. The wire value is the lower-case extension. + */ +public enum FileDataFormat { + BMP, + CSV, + DCM, + DOC, + DOCX, + GIF, + JPEG, + JPG, + JSON, + JSONL, + MP3, + PDF, + PNG, + PPT, + PPTX, + TIF, + TIFF, + TXT, + WAV, + XLS, + XLSX, + XML, + ZIP; +} diff --git a/common/src/main/java/com/skyflow/detect/FileMapping.java b/common/src/main/java/com/skyflow/detect/FileMapping.java new file mode 100644 index 00000000..da0663b0 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/FileMapping.java @@ -0,0 +1,133 @@ +package com.skyflow.detect; + +/** + * Maps an input file location to output locations. File inputs only. + */ +public final class FileMapping { + private final String source; + private final String destination; + private final String outputFileNameSuffix; + private final String entitiesDestination; + private final String objectEntitiesDestination; + + private FileMapping(FileMappingBuilder builder) { + this.source = builder.source; + this.destination = builder.destination; + this.outputFileNameSuffix = builder.outputFileNameSuffix; + this.entitiesDestination = builder.entitiesDestination; + this.objectEntitiesDestination = builder.objectEntitiesDestination; + } + + /** + * @return a new builder + */ + public static FileMappingBuilder builder() { + return new FileMappingBuilder(); + } + + /** + * @return Source location. + */ + public String getSource() { + return source; + } + + /** + * @return Destination for the processed file. + */ + public String getDestination() { + return destination; + } + + /** + * @return Suffix appended to the processed file name. + */ + public String getOutputFileNameSuffix() { + return outputFileNameSuffix; + } + + /** + * @return Destination for the detected entities file. + */ + public String getEntitiesDestination() { + return entitiesDestination; + } + + /** + * @return Destination for the detected object entities file. + */ + public String getObjectEntitiesDestination() { + return objectEntitiesDestination; + } + + @Override + public String toString() { + return "FileMapping{" + + "source=" + source + + ", destination=" + destination + + ", outputFileNameSuffix=" + outputFileNameSuffix + + ", entitiesDestination=" + entitiesDestination + + ", objectEntitiesDestination=" + objectEntitiesDestination + + '}'; + } + + public static final class FileMappingBuilder { + private String source; + private String destination; + private String outputFileNameSuffix; + private String entitiesDestination; + private String objectEntitiesDestination; + + private FileMappingBuilder() { + } + + /** + * @param source Source location. + * @return this builder + */ + public FileMappingBuilder source(String source) { + this.source = source; + return this; + } + + /** + * @param destination Destination for the processed file. + * @return this builder + */ + public FileMappingBuilder destination(String destination) { + this.destination = destination; + return this; + } + + /** + * @param outputFileNameSuffix Suffix appended to the processed file name. + * @return this builder + */ + public FileMappingBuilder outputFileNameSuffix(String outputFileNameSuffix) { + this.outputFileNameSuffix = outputFileNameSuffix; + return this; + } + + /** + * @param entitiesDestination Destination for the detected entities file. + * @return this builder + */ + public FileMappingBuilder entitiesDestination(String entitiesDestination) { + this.entitiesDestination = entitiesDestination; + return this; + } + + /** + * @param objectEntitiesDestination Destination for the detected object entities file. + * @return this builder + */ + public FileMappingBuilder objectEntitiesDestination(String objectEntitiesDestination) { + this.objectEntitiesDestination = objectEntitiesDestination; + return this; + } + + public FileMapping build() { + return new FileMapping(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/FileOutput.java b/common/src/main/java/com/skyflow/detect/FileOutput.java new file mode 100644 index 00000000..a33cafca --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/FileOutput.java @@ -0,0 +1,46 @@ +package com.skyflow.detect; + +/** + * One output artifact of a Detect file run. + */ +public final class FileOutput { + private final String processedFile; + private final String processedFileType; + private final FileDataFormat processedFileExtension; + + public FileOutput(String processedFile, String processedFileType, FileDataFormat processedFileExtension) { + this.processedFile = processedFile; + this.processedFileType = processedFileType; + this.processedFileExtension = processedFileExtension; + } + + /** + * @return Base64 content or presigned URL, according to the run's outputType. + */ + public String getProcessedFile() { + return processedFile; + } + + /** + * @return Kind of output, for example REDACTED_FILE or ENTITIES. Reported as a string because the API does not enumerate it. + */ + public String getProcessedFileType() { + return processedFileType; + } + + /** + * @return Format of the output, or null when not reported. + */ + public FileDataFormat getProcessedFileExtension() { + return processedFileExtension; + } + + @Override + public String toString() { + return "FileOutput{" + + "processedFile=" + processedFile + + ", processedFileType=" + processedFileType + + ", processedFileExtension=" + processedFileExtension + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/GetRunRequest.java b/common/src/main/java/com/skyflow/detect/GetRunRequest.java new file mode 100644 index 00000000..21a02689 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/GetRunRequest.java @@ -0,0 +1,53 @@ +package com.skyflow.detect; + +/** + * Request for {@code getRun}: retrieves the status and outputs of a Detect file run. + */ +public final class GetRunRequest { + private final String runId; + + private GetRunRequest(GetRunRequestBuilder builder) { + this.runId = builder.runId; + } + + /** + * @return a new builder + */ + public static GetRunRequestBuilder builder() { + return new GetRunRequestBuilder(); + } + + /** + * @return Run id returned by {@code deidentifyFile}. Required. + */ + public String getRunId() { + return runId; + } + + @Override + public String toString() { + return "GetRunRequest{" + + "runId=" + runId + + '}'; + } + + public static final class GetRunRequestBuilder { + private String runId; + + private GetRunRequestBuilder() { + } + + /** + * @param runId Run id returned by {@code deidentifyFile}. Required. + * @return this builder + */ + public GetRunRequestBuilder runId(String runId) { + this.runId = runId; + return this; + } + + public GetRunRequest build() { + return new GetRunRequest(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/GetRunResponse.java b/common/src/main/java/com/skyflow/detect/GetRunResponse.java new file mode 100644 index 00000000..e8ffbc27 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/GetRunResponse.java @@ -0,0 +1,78 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * Response of {@code getRun}. Output, outputType and metrics are populated only once the run has succeeded. + */ +public final class GetRunResponse { + private final String runId; + private final DetectRunStatus status; + private final DataSourceType outputType; + private final List output; + private final Metrics metrics; + private final String message; + + public GetRunResponse(String runId, DetectRunStatus status, DataSourceType outputType, List output, Metrics metrics, String message) { + this.runId = runId; + this.status = status; + this.outputType = outputType; + this.output = output; + this.metrics = metrics; + this.message = message; + } + + /** + * @return Run id that was queried. + */ + public String getRunId() { + return runId; + } + + /** + * @return Run status. UNKNOWN when the API did not report one. + */ + public DetectRunStatus getStatus() { + return status; + } + + /** + * @return How output files are delivered. Null while the run is pending. + */ + public DataSourceType getOutputType() { + return outputType; + } + + /** + * @return Output artifacts. Empty while the run is pending, never null. + */ + public List getOutput() { + return output; + } + + /** + * @return Processing metrics. Null while the run is pending. + */ + public Metrics getMetrics() { + return metrics; + } + + /** + * @return Failure detail when status is FAILED. + */ + public String getMessage() { + return message; + } + + @Override + public String toString() { + return "GetRunResponse{" + + "runId=" + runId + + ", status=" + status + + ", outputType=" + outputType + + ", output=" + output + + ", metrics=" + metrics + + ", message=" + message + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/GuardrailsValidation.java b/common/src/main/java/com/skyflow/detect/GuardrailsValidation.java new file mode 100644 index 00000000..1d6f0f8c --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/GuardrailsValidation.java @@ -0,0 +1,11 @@ +package com.skyflow.detect; + +/** + * Overall result of a guardrails check. + */ +public enum GuardrailsValidation { + PASSED, + FAILED, + /** The API reported a value this SDK version does not know. */ + UNKNOWN; +} diff --git a/common/src/main/java/com/skyflow/detect/Image.java b/common/src/main/java/com/skyflow/detect/Image.java new file mode 100644 index 00000000..f1e33135 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Image.java @@ -0,0 +1,93 @@ +package com.skyflow.detect; + +/** + * Image processing options. + */ +public final class Image { + private final Boolean outputProcessedImage; + private final Boolean outputOcrText; + private final MaskingMethod maskingMethod; + + private Image(ImageBuilder builder) { + this.outputProcessedImage = builder.outputProcessedImage; + this.outputOcrText = builder.outputOcrText; + this.maskingMethod = builder.maskingMethod; + } + + /** + * @return a new builder + */ + public static ImageBuilder builder() { + return new ImageBuilder(); + } + + /** + * @return Whether to return the processed image. + */ + public Boolean getOutputProcessedImage() { + return outputProcessedImage; + } + + /** + * @return Whether to return OCR text. + */ + public Boolean getOutputOcrText() { + return outputOcrText; + } + + /** + * @return Masking method for detected regions. + */ + public MaskingMethod getMaskingMethod() { + return maskingMethod; + } + + @Override + public String toString() { + return "Image{" + + "outputProcessedImage=" + outputProcessedImage + + ", outputOcrText=" + outputOcrText + + ", maskingMethod=" + maskingMethod + + '}'; + } + + public static final class ImageBuilder { + private Boolean outputProcessedImage; + private Boolean outputOcrText; + private MaskingMethod maskingMethod; + + private ImageBuilder() { + } + + /** + * @param outputProcessedImage Whether to return the processed image. + * @return this builder + */ + public ImageBuilder outputProcessedImage(Boolean outputProcessedImage) { + this.outputProcessedImage = outputProcessedImage; + return this; + } + + /** + * @param outputOcrText Whether to return OCR text. + * @return this builder + */ + public ImageBuilder outputOcrText(Boolean outputOcrText) { + this.outputOcrText = outputOcrText; + return this; + } + + /** + * @param maskingMethod Masking method for detected regions. + * @return this builder + */ + public ImageBuilder maskingMethod(MaskingMethod maskingMethod) { + this.maskingMethod = maskingMethod; + return this; + } + + public Image build() { + return new Image(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/MaskingMethod.java b/common/src/main/java/com/skyflow/detect/MaskingMethod.java new file mode 100644 index 00000000..38402c52 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/MaskingMethod.java @@ -0,0 +1,10 @@ +package com.skyflow.detect; + +/** + * Masking method applied to detected regions in images. + */ +public enum MaskingMethod { + NONE, + BLUR, + BLACKBOX; +} diff --git a/common/src/main/java/com/skyflow/detect/Media.java b/common/src/main/java/com/skyflow/detect/Media.java new file mode 100644 index 00000000..af6f24ac --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Media.java @@ -0,0 +1,93 @@ +package com.skyflow.detect; + +/** + * Media-type specific processing options. File inputs only. + */ +public final class Media { + private final Audio audio; + private final Document document; + private final Image image; + + private Media(MediaBuilder builder) { + this.audio = builder.audio; + this.document = builder.document; + this.image = builder.image; + } + + /** + * @return a new builder + */ + public static MediaBuilder builder() { + return new MediaBuilder(); + } + + /** + * @return Audio options. + */ + public Audio getAudio() { + return audio; + } + + /** + * @return Document options. + */ + public Document getDocument() { + return document; + } + + /** + * @return Image options. + */ + public Image getImage() { + return image; + } + + @Override + public String toString() { + return "Media{" + + "audio=" + audio + + ", document=" + document + + ", image=" + image + + '}'; + } + + public static final class MediaBuilder { + private Audio audio; + private Document document; + private Image image; + + private MediaBuilder() { + } + + /** + * @param audio Audio options. + * @return this builder + */ + public MediaBuilder audio(Audio audio) { + this.audio = audio; + return this; + } + + /** + * @param document Document options. + * @return this builder + */ + public MediaBuilder document(Document document) { + this.document = document; + return this; + } + + /** + * @param image Image options. + * @return this builder + */ + public MediaBuilder image(Image image) { + this.image = image; + return this; + } + + public Media build() { + return new Media(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/Metrics.java b/common/src/main/java/com/skyflow/detect/Metrics.java new file mode 100644 index 00000000..46becb12 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Metrics.java @@ -0,0 +1,76 @@ +package com.skyflow.detect; + +/** + * Processing metrics returned by Detect operations. + */ +public final class Metrics { + private final Double size; + private final Integer wordCount; + private final Integer characterCount; + private final Integer slides; + private final Integer pages; + private final Double duration; + + public Metrics(Double size, Integer wordCount, Integer characterCount, Integer slides, Integer pages, Double duration) { + this.size = size; + this.wordCount = wordCount; + this.characterCount = characterCount; + this.slides = slides; + this.pages = pages; + this.duration = duration; + } + + /** + * @return Input size in kilobytes. + */ + public Double getSize() { + return size; + } + + /** + * @return Number of words. + */ + public Integer getWordCount() { + return wordCount; + } + + /** + * @return Number of characters. + */ + public Integer getCharacterCount() { + return characterCount; + } + + /** + * @return Number of slides. + */ + public Integer getSlides() { + return slides; + } + + /** + * @return Number of pages. + */ + public Integer getPages() { + return pages; + } + + /** + * @return Media duration in seconds. + */ + public Double getDuration() { + return duration; + } + + @Override + public String toString() { + return "Metrics{" + + "size=" + size + + ", wordCount=" + wordCount + + ", characterCount=" + characterCount + + ", slides=" + slides + + ", pages=" + pages + + ", duration=" + duration + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/ObjectDeidentificationType.java b/common/src/main/java/com/skyflow/detect/ObjectDeidentificationType.java new file mode 100644 index 00000000..13f3fd6e --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ObjectDeidentificationType.java @@ -0,0 +1,10 @@ +package com.skyflow.detect; + +/** + * How a detected visual object is handled. + */ +public enum ObjectDeidentificationType { + UNKNOWN, + REDACT, + UNREDACT; +} diff --git a/common/src/main/java/com/skyflow/detect/ObjectEntity.java b/common/src/main/java/com/skyflow/detect/ObjectEntity.java new file mode 100644 index 00000000..1f62853b --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ObjectEntity.java @@ -0,0 +1,73 @@ +package com.skyflow.detect; + +/** + * Configures detection of a visual object type in images or video. + */ +public final class ObjectEntity { + private final ObjectEntityType entityType; + private final ObjectDeidentificationType deidentificationType; + + private ObjectEntity(ObjectEntityBuilder builder) { + this.entityType = builder.entityType; + this.deidentificationType = builder.deidentificationType; + } + + /** + * @return a new builder + */ + public static ObjectEntityBuilder builder() { + return new ObjectEntityBuilder(); + } + + /** + * @return Object type this rule applies to. + */ + public ObjectEntityType getEntityType() { + return entityType; + } + + /** + * @return How matches are handled. + */ + public ObjectDeidentificationType getDeidentificationType() { + return deidentificationType; + } + + @Override + public String toString() { + return "ObjectEntity{" + + "entityType=" + entityType + + ", deidentificationType=" + deidentificationType + + '}'; + } + + public static final class ObjectEntityBuilder { + private ObjectEntityType entityType; + private ObjectDeidentificationType deidentificationType; + + private ObjectEntityBuilder() { + } + + /** + * @param entityType Object type this rule applies to. + * @return this builder + */ + public ObjectEntityBuilder entityType(ObjectEntityType entityType) { + this.entityType = entityType; + return this; + } + + /** + * @param deidentificationType How matches are handled. + * @return this builder + */ + public ObjectEntityBuilder deidentificationType(ObjectDeidentificationType deidentificationType) { + this.deidentificationType = deidentificationType; + return this; + } + + public ObjectEntity build() { + return new ObjectEntity(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/ObjectEntityType.java b/common/src/main/java/com/skyflow/detect/ObjectEntityType.java new file mode 100644 index 00000000..679917c7 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ObjectEntityType.java @@ -0,0 +1,13 @@ +package com.skyflow.detect; + +/** + * Visual objects Skyflow Detect can identify in images and video. + */ +public enum ObjectEntityType { + NONE, + FACE, + LICENSE_PLATE, + LOGO, + SIGNATURE, + ALL; +} diff --git a/common/src/main/java/com/skyflow/detect/OutputTranscriptionType.java b/common/src/main/java/com/skyflow/detect/OutputTranscriptionType.java new file mode 100644 index 00000000..ed2638ed --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/OutputTranscriptionType.java @@ -0,0 +1,12 @@ +package com.skyflow.detect; + +/** + * Transcription output produced for audio inputs. + */ +public enum OutputTranscriptionType { + NONE, + TRANSCRIPTION, + MEDICAL_TRANSCRIPTION, + DIARIZED_TRANSCRIPTION, + MEDICAL_DIARIZED_TRANSCRIPTION; +} diff --git a/common/src/main/java/com/skyflow/detect/Pdf.java b/common/src/main/java/com/skyflow/detect/Pdf.java new file mode 100644 index 00000000..d147d632 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Pdf.java @@ -0,0 +1,93 @@ +package com.skyflow.detect; + +/** + * PDF processing options. + */ +public final class Pdf { + private final PdfProcessingMode processingMode; + private final Integer density; + private final Integer maxResolution; + + private Pdf(PdfBuilder builder) { + this.processingMode = builder.processingMode; + this.density = builder.density; + this.maxResolution = builder.maxResolution; + } + + /** + * @return a new builder + */ + public static PdfBuilder builder() { + return new PdfBuilder(); + } + + /** + * @return Processing mode. + */ + public PdfProcessingMode getProcessingMode() { + return processingMode; + } + + /** + * @return Rendering density (DPI). + */ + public Integer getDensity() { + return density; + } + + /** + * @return Maximum rendering resolution. + */ + public Integer getMaxResolution() { + return maxResolution; + } + + @Override + public String toString() { + return "Pdf{" + + "processingMode=" + processingMode + + ", density=" + density + + ", maxResolution=" + maxResolution + + '}'; + } + + public static final class PdfBuilder { + private PdfProcessingMode processingMode; + private Integer density; + private Integer maxResolution; + + private PdfBuilder() { + } + + /** + * @param processingMode Processing mode. + * @return this builder + */ + public PdfBuilder processingMode(PdfProcessingMode processingMode) { + this.processingMode = processingMode; + return this; + } + + /** + * @param density Rendering density (DPI). + * @return this builder + */ + public PdfBuilder density(Integer density) { + this.density = density; + return this; + } + + /** + * @param maxResolution Maximum rendering resolution. + * @return this builder + */ + public PdfBuilder maxResolution(Integer maxResolution) { + this.maxResolution = maxResolution; + return this; + } + + public Pdf build() { + return new Pdf(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/PdfProcessingMode.java b/common/src/main/java/com/skyflow/detect/PdfProcessingMode.java new file mode 100644 index 00000000..f32399ba --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/PdfProcessingMode.java @@ -0,0 +1,10 @@ +package com.skyflow.detect; + +/** + * How PDF documents are processed. + */ +public enum PdfProcessingMode { + NONE, + OCR, + TEXT_LAYER; +} diff --git a/common/src/main/java/com/skyflow/detect/PollOptions.java b/common/src/main/java/com/skyflow/detect/PollOptions.java new file mode 100644 index 00000000..c1aa656a --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/PollOptions.java @@ -0,0 +1,91 @@ +package com.skyflow.detect; + +/** + * Opts {@code deidentifyFile} into submit-and-poll mode. When present, the SDK polls the run with + * exponential backoff (1, 2, 4, 8, 16, then 32 seconds) until it reaches a terminal status, the + * wait time is used up, or the attempt limit is hit. An empty {@code PollOptions.builder().build()} + * uses the defaults. + */ +public final class PollOptions { + public static final int DEFAULT_WAIT_TIME_SECONDS = 60; + public static final int MAX_WAIT_TIME_SECONDS = 300; + public static final int DEFAULT_MAX_ATTEMPTS = 23; + public static final int MAX_MAX_ATTEMPTS = 23; + + private final Integer waitTime; + private final Integer maxAttempts; + + private PollOptions(PollOptionsBuilder builder) { + this.waitTime = builder.waitTime; + this.maxAttempts = builder.maxAttempts; + } + + /** + * @return a new builder + */ + public static PollOptionsBuilder builder() { + return new PollOptionsBuilder(); + } + + /** + * @return Maximum total seconds to keep polling, or null for the default of 60. At most 300. + */ + public Integer getWaitTime() { + return waitTime; + } + + /** + * @return Maximum number of run lookups, or null for the default of 23. At most 23. + */ + public Integer getMaxAttempts() { + return maxAttempts; + } + + /** @return the wait time with the default applied */ + public int effectiveWaitTime() { + return waitTime == null ? DEFAULT_WAIT_TIME_SECONDS : waitTime; + } + + /** @return the attempt limit with the default applied */ + public int effectiveMaxAttempts() { + return maxAttempts == null ? DEFAULT_MAX_ATTEMPTS : maxAttempts; + } + + @Override + public String toString() { + return "PollOptions{" + + "waitTime=" + waitTime + + ", maxAttempts=" + maxAttempts + + '}'; + } + + public static final class PollOptionsBuilder { + private Integer waitTime; + private Integer maxAttempts; + + private PollOptionsBuilder() { + } + + /** + * @param waitTime Maximum total seconds to keep polling. 1 to 300; default 60. + * @return this builder + */ + public PollOptionsBuilder waitTime(Integer waitTime) { + this.waitTime = waitTime; + return this; + } + + /** + * @param maxAttempts Maximum number of run lookups. 1 to 23; default 23. + * @return this builder + */ + public PollOptionsBuilder maxAttempts(Integer maxAttempts) { + this.maxAttempts = maxAttempts; + return this; + } + + public PollOptions build() { + return new PollOptions(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/RedactionLevel.java b/common/src/main/java/com/skyflow/detect/RedactionLevel.java new file mode 100644 index 00000000..74f04f1e --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/RedactionLevel.java @@ -0,0 +1,113 @@ +package com.skyflow.detect; + +/** + * Controls how one group of tokens is rendered when re-identifying. Supply exactly one source (entityName or tokenGroupName) and exactly one replacement (redactionType or redactionPattern). + */ +public final class RedactionLevel { + private final EntityType entityName; + private final RedactionType redactionType; + private final String tokenGroupName; + private final String redactionPattern; + + private RedactionLevel(RedactionLevelBuilder builder) { + this.entityName = builder.entityName; + this.redactionType = builder.redactionType; + this.tokenGroupName = builder.tokenGroupName; + this.redactionPattern = builder.redactionPattern; + } + + /** + * @return a new builder + */ + public static RedactionLevelBuilder builder() { + return new RedactionLevelBuilder(); + } + + /** + * @return Entity to target. skyvault vaults. + */ + public EntityType getEntityName() { + return entityName; + } + + /** + * @return Replacement rendering. skyvault vaults. + */ + public RedactionType getRedactionType() { + return redactionType; + } + + /** + * @return Token group to target. flowvault vaults. + */ + public String getTokenGroupName() { + return tokenGroupName; + } + + /** + * @return Named redaction pattern to apply. flowvault vaults. + */ + public String getRedactionPattern() { + return redactionPattern; + } + + @Override + public String toString() { + return "RedactionLevel{" + + "entityName=" + entityName + + ", redactionType=" + redactionType + + ", tokenGroupName=" + tokenGroupName + + ", redactionPattern=" + redactionPattern + + '}'; + } + + public static final class RedactionLevelBuilder { + private EntityType entityName; + private RedactionType redactionType; + private String tokenGroupName; + private String redactionPattern; + + private RedactionLevelBuilder() { + } + + /** + * @param entityName Entity to target. skyvault vaults. + * @return this builder + */ + public RedactionLevelBuilder entityName(EntityType entityName) { + this.entityName = entityName; + return this; + } + + /** + * @param redactionType Replacement rendering. skyvault vaults. + * @return this builder + */ + public RedactionLevelBuilder redactionType(RedactionType redactionType) { + this.redactionType = redactionType; + return this; + } + + /** + * @param tokenGroupName Token group to target. flowvault vaults. + * @return this builder + */ + public RedactionLevelBuilder tokenGroupName(String tokenGroupName) { + this.tokenGroupName = tokenGroupName; + return this; + } + + /** + * @param redactionPattern Named redaction pattern to apply. flowvault vaults. + * @return this builder + */ + public RedactionLevelBuilder redactionPattern(String redactionPattern) { + this.redactionPattern = redactionPattern; + return this; + } + + public RedactionLevel build() { + return new RedactionLevel(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/RedactionType.java b/common/src/main/java/com/skyflow/detect/RedactionType.java new file mode 100644 index 00000000..87b3e891 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/RedactionType.java @@ -0,0 +1,11 @@ +package com.skyflow.detect; + +/** + * How a token is rendered when re-identifying (skyvault vaults). + */ +public enum RedactionType { + PLAIN_TEXT, + MASKED, + DEFAULT, + REDACTED; +} diff --git a/common/src/main/java/com/skyflow/detect/ReidentifyFileRequest.java b/common/src/main/java/com/skyflow/detect/ReidentifyFileRequest.java new file mode 100644 index 00000000..9aa7135e --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ReidentifyFileRequest.java @@ -0,0 +1,118 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * Request for {@code reidentifyFile}. Supply the file through exactly one {@link DataSourceType}: + * the base64-encoded content, the skyflow id of a vault record that holds the file, or an S3 + * presigned URL. The vault id is filled in by the controller. + */ +public final class ReidentifyFileRequest { + private final DataSourceType dataSource; + private final String value; + private final FileDataFormat dataFormat; + private final List redactionLevel; + + private ReidentifyFileRequest(ReidentifyFileRequestBuilder builder) { + this.dataSource = builder.dataSource; + this.value = builder.value; + this.dataFormat = builder.dataFormat; + this.redactionLevel = builder.redactionLevel; + } + + /** + * @return a new builder + */ + public static ReidentifyFileRequestBuilder builder() { + return new ReidentifyFileRequestBuilder(); + } + + /** + * @return How {@code value} supplies the file. Required. + */ + public DataSourceType getDataSource() { + return dataSource; + } + + /** + * @return Base64 content, skyflow id or presigned URL of the file, according to {@code dataSource}. Required. + */ + public String getValue() { + return value; + } + + /** + * @return Format of the file. Optional; the API infers it when omitted. Re-identification supports text formats + * such as TXT, CSV, JSON, JSONL, XML, DOCX, XLSX and PPTX. + */ + public FileDataFormat getDataFormat() { + return dataFormat; + } + + /** + * @return Optional per-group rendering rules. + */ + public List getRedactionLevel() { + return redactionLevel; + } + + @Override + public String toString() { + return "ReidentifyFileRequest{" + + "dataSource=" + dataSource + + ", value=" + value + + ", dataFormat=" + dataFormat + + ", redactionLevel=" + redactionLevel + + '}'; + } + + public static final class ReidentifyFileRequestBuilder { + private DataSourceType dataSource; + private String value; + private FileDataFormat dataFormat; + private List redactionLevel; + + private ReidentifyFileRequestBuilder() { + } + + /** + * @param dataSource How {@code value} supplies the file. Required. + * @return this builder + */ + public ReidentifyFileRequestBuilder dataSource(DataSourceType dataSource) { + this.dataSource = dataSource; + return this; + } + + /** + * @param value Base64 content, skyflow id or presigned URL of the file, according to {@code dataSource}. Required. + * @return this builder + */ + public ReidentifyFileRequestBuilder value(String value) { + this.value = value; + return this; + } + + /** + * @param dataFormat Format of the file. Optional. + * @return this builder + */ + public ReidentifyFileRequestBuilder dataFormat(FileDataFormat dataFormat) { + this.dataFormat = dataFormat; + return this; + } + + /** + * @param redactionLevel Optional per-group rendering rules. + * @return this builder + */ + public ReidentifyFileRequestBuilder redactionLevel(List redactionLevel) { + this.redactionLevel = redactionLevel; + return this; + } + + public ReidentifyFileRequest build() { + return new ReidentifyFileRequest(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/ReidentifyFileResponse.java b/common/src/main/java/com/skyflow/detect/ReidentifyFileResponse.java new file mode 100644 index 00000000..17d32f3e --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ReidentifyFileResponse.java @@ -0,0 +1,59 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * Response of {@code reidentifyFile}. File re-identification is synchronous, so a {@code SUCCESS} + * status carries the output in the same response. + */ +public final class ReidentifyFileResponse { + private final DetectRunStatus status; + private final DataSourceType outputType; + private final List output; + private final Metrics metrics; + + public ReidentifyFileResponse(DetectRunStatus status, DataSourceType outputType, List output, Metrics metrics) { + this.status = status; + this.outputType = outputType; + this.output = output; + this.metrics = metrics; + } + + /** + * @return Processing status. UNKNOWN when the API did not report one. + */ + public DetectRunStatus getStatus() { + return status; + } + + /** + * @return How output files are delivered, or null when not reported. + */ + public DataSourceType getOutputType() { + return outputType; + } + + /** + * @return Output artifacts. Empty when none were returned, never null. + */ + public List getOutput() { + return output; + } + + /** + * @return Processing metrics, or null when not reported. + */ + public Metrics getMetrics() { + return metrics; + } + + @Override + public String toString() { + return "ReidentifyFileResponse{" + + "status=" + status + + ", outputType=" + outputType + + ", output=" + output + + ", metrics=" + metrics + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/ReidentifyStringRequest.java b/common/src/main/java/com/skyflow/detect/ReidentifyStringRequest.java new file mode 100644 index 00000000..23626297 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ReidentifyStringRequest.java @@ -0,0 +1,75 @@ +package com.skyflow.detect; + +import java.util.List; + +/** + * Request for {@code reidentifyString}. + */ +public final class ReidentifyStringRequest { + private final String text; + private final List redactionLevel; + + private ReidentifyStringRequest(ReidentifyStringRequestBuilder builder) { + this.text = builder.text; + this.redactionLevel = builder.redactionLevel; + } + + /** + * @return a new builder + */ + public static ReidentifyStringRequestBuilder builder() { + return new ReidentifyStringRequestBuilder(); + } + + /** + * @return Text containing tokens to re-identify. Required. + */ + public String getText() { + return text; + } + + /** + * @return Optional per-group rendering rules. + */ + public List getRedactionLevel() { + return redactionLevel; + } + + @Override + public String toString() { + return "ReidentifyStringRequest{" + + "text=" + text + + ", redactionLevel=" + redactionLevel + + '}'; + } + + public static final class ReidentifyStringRequestBuilder { + private String text; + private List redactionLevel; + + private ReidentifyStringRequestBuilder() { + } + + /** + * @param text Text containing tokens to re-identify. Required. + * @return this builder + */ + public ReidentifyStringRequestBuilder text(String text) { + this.text = text; + return this; + } + + /** + * @param redactionLevel Optional per-group rendering rules. + * @return this builder + */ + public ReidentifyStringRequestBuilder redactionLevel(List redactionLevel) { + this.redactionLevel = redactionLevel; + return this; + } + + public ReidentifyStringRequest build() { + return new ReidentifyStringRequest(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/ReidentifyStringResponse.java b/common/src/main/java/com/skyflow/detect/ReidentifyStringResponse.java new file mode 100644 index 00000000..e1825bf2 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ReidentifyStringResponse.java @@ -0,0 +1,36 @@ +package com.skyflow.detect; + +/** + * Response of {@code reidentifyString}. + */ +public final class ReidentifyStringResponse { + private final String processedText; + private final Metrics metrics; + + public ReidentifyStringResponse(String processedText, Metrics metrics) { + this.processedText = processedText; + this.metrics = metrics; + } + + /** + * @return Re-identified text. + */ + public String getProcessedText() { + return processedText; + } + + /** + * @return Processing metrics. + */ + public Metrics getMetrics() { + return metrics; + } + + @Override + public String toString() { + return "ReidentifyStringResponse{" + + "processedText=" + processedText + + ", metrics=" + metrics + + '}'; + } +} diff --git a/common/src/main/java/com/skyflow/detect/ReturnEntitiesType.java b/common/src/main/java/com/skyflow/detect/ReturnEntitiesType.java new file mode 100644 index 00000000..3ba4fa79 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ReturnEntitiesType.java @@ -0,0 +1,10 @@ +package com.skyflow.detect; + +/** + * Controls which detected entities are returned in the response. + */ +public enum ReturnEntitiesType { + EXCLUDE_SENSITIVE_DATA, + ALL, + NONE; +} diff --git a/common/src/main/java/com/skyflow/detect/ShiftDates.java b/common/src/main/java/com/skyflow/detect/ShiftDates.java new file mode 100644 index 00000000..fd4adc24 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/ShiftDates.java @@ -0,0 +1,73 @@ +package com.skyflow.detect; + +/** + * Shifts detected dates by a random number of days within the given range. + */ +public final class ShiftDates { + private final Integer minDays; + private final Integer maxDays; + + private ShiftDates(ShiftDatesBuilder builder) { + this.minDays = builder.minDays; + this.maxDays = builder.maxDays; + } + + /** + * @return a new builder + */ + public static ShiftDatesBuilder builder() { + return new ShiftDatesBuilder(); + } + + /** + * @return Minimum number of days to shift. + */ + public Integer getMinDays() { + return minDays; + } + + /** + * @return Maximum number of days to shift. + */ + public Integer getMaxDays() { + return maxDays; + } + + @Override + public String toString() { + return "ShiftDates{" + + "minDays=" + minDays + + ", maxDays=" + maxDays + + '}'; + } + + public static final class ShiftDatesBuilder { + private Integer minDays; + private Integer maxDays; + + private ShiftDatesBuilder() { + } + + /** + * @param minDays Minimum number of days to shift. + * @return this builder + */ + public ShiftDatesBuilder minDays(Integer minDays) { + this.minDays = minDays; + return this; + } + + /** + * @param maxDays Maximum number of days to shift. + * @return this builder + */ + public ShiftDatesBuilder maxDays(Integer maxDays) { + this.maxDays = maxDays; + return this; + } + + public ShiftDates build() { + return new ShiftDates(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/Transformation.java b/common/src/main/java/com/skyflow/detect/Transformation.java new file mode 100644 index 00000000..5fb9cb69 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/Transformation.java @@ -0,0 +1,53 @@ +package com.skyflow.detect; + +/** + * Transformations applied to detected entities before they are written to the output. + */ +public final class Transformation { + private final ShiftDates shiftDates; + + private Transformation(TransformationBuilder builder) { + this.shiftDates = builder.shiftDates; + } + + /** + * @return a new builder + */ + public static TransformationBuilder builder() { + return new TransformationBuilder(); + } + + /** + * @return Date shifting configuration. + */ + public ShiftDates getShiftDates() { + return shiftDates; + } + + @Override + public String toString() { + return "Transformation{" + + "shiftDates=" + shiftDates + + '}'; + } + + public static final class TransformationBuilder { + private ShiftDates shiftDates; + + private TransformationBuilder() { + } + + /** + * @param shiftDates Date shifting configuration. + * @return this builder + */ + public TransformationBuilder shiftDates(ShiftDates shiftDates) { + this.shiftDates = shiftDates; + return this; + } + + public Transformation build() { + return new Transformation(this); + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/internal/DeidentifyFileFlow.java b/common/src/main/java/com/skyflow/detect/internal/DeidentifyFileFlow.java new file mode 100644 index 00000000..4d825983 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/internal/DeidentifyFileFlow.java @@ -0,0 +1,41 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyFileResponse; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.polling.RunPoller; +import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.BaseUtils; +import com.skyflow.utils.logger.LogUtil; + +/** + * Everything {@code deidentifyFile} does after the submit call, shared by every SDK: decide whether to + * poll, poll, merge the run into the response, and write outputs for file-based requests. Each + * controller performs the submit itself and hands the run id here. + */ +public final class DeidentifyFileFlow { + private DeidentifyFileFlow() { + } + + public static DeidentifyFileResponse complete(DeidentifyFileRequest request, String runId, RunPoller.RunFetcher fetcher) + throws SkyflowException { + return complete(request, runId, fetcher, Thread::sleep); + } + + static DeidentifyFileResponse complete(DeidentifyFileRequest request, String runId, RunPoller.RunFetcher fetcher, + RunPoller.Sleeper sleeper) throws SkyflowException { + if (request.getPollOptions() == null || runId == null) { + LogUtil.printInfoLog(BaseUtils.parameterizedString(InfoLogs.DEIDENTIFY_FILE_RUN_SUBMITTED.getLog(), String.valueOf(runId))); + return DetectResponseMapper.submittedDeidentifyFileResponse(runId); + } + GetRunResponse run = RunPoller.poll(runId, request.getPollOptions(), fetcher, sleeper); + DeidentifyFileResponse response = DetectResponseMapper.toDeidentifyFileResponse(runId, run); + if (response.getStatus() == DetectRunStatus.SUCCESS && request.getFile() != null) { + FileOutputWriter.write(response.getOutput(), response.getOutputType(), request.getFile().getName(), + request.getOutputDirectory()); + } + return response; + } +} diff --git a/common/src/main/java/com/skyflow/detect/internal/DetectRequestMapper.java b/common/src/main/java/com/skyflow/detect/internal/DetectRequestMapper.java new file mode 100644 index 00000000..42ef0faf --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/internal/DetectRequestMapper.java @@ -0,0 +1,407 @@ +package com.skyflow.detect.internal; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +import com.skyflow.detect.Audio; +import com.skyflow.detect.Bleep; +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.CustomType; +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.Detect; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.Document; +import com.skyflow.detect.Entity; +import com.skyflow.detect.FileMapping; +import com.skyflow.detect.Image; +import com.skyflow.detect.Media; +import com.skyflow.detect.ObjectEntity; +import com.skyflow.detect.Pdf; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.detect.ShiftDates; +import com.skyflow.detect.Transformation; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.DeidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.resources.filesv2.types.DeidentifyFileRequestV2DataFormat; +import com.skyflow.generated.detect.rest.resources.filesv2.types.DeidentifyFileRequestV2DataSource; +import com.skyflow.generated.detect.rest.resources.guardrailsv2.requests.DetectGuardrailsRequestV2; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.utils.BaseUtils; +import com.skyflow.utils.logger.LogUtil; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.DeidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.ReidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.types.AudioV2; +import com.skyflow.generated.detect.rest.types.AudioV2Bleep; +import com.skyflow.generated.detect.rest.types.AudioV2OutputTranscription; +import com.skyflow.generated.detect.rest.types.DetectConfigV2; +import com.skyflow.generated.detect.rest.types.DetectCustomTypes; +import com.skyflow.generated.detect.rest.types.DetectEntity; +import com.skyflow.generated.detect.rest.types.DetectEntityDeidentificationType; +import com.skyflow.generated.detect.rest.types.DetectEntityEntityType; +import com.skyflow.generated.detect.rest.types.DetectObjectEntity; +import com.skyflow.generated.detect.rest.types.DetectObjectEntityDeidentificationType; +import com.skyflow.generated.detect.rest.types.DetectObjectEntityEntityType; +import com.skyflow.generated.detect.rest.types.DetectReturnEntities; +import com.skyflow.generated.detect.rest.types.DocumentV2; +import com.skyflow.generated.detect.rest.types.DocumentV2Pdf; +import com.skyflow.generated.detect.rest.types.DocumentV2PdfProcessingMode; +import com.skyflow.generated.detect.rest.types.EntityTransformation; +import com.skyflow.generated.detect.rest.types.ImageV2; +import com.skyflow.generated.detect.rest.types.ImageV2MaskingMethod; +import com.skyflow.generated.detect.rest.types.RedactionLevelEntityName; +import com.skyflow.generated.detect.rest.types.RedactionLevelRedactionType; +import com.skyflow.generated.detect.rest.types.TransformationShiftDates; + +/** + * Converts public SDK request models into generated V2 API requests. Internal to the SDK. + */ +public final class DetectRequestMapper { + private DetectRequestMapper() { + } + + public static DeidentifyStringRequestV2 toDeidentifyStringRequest(DeidentifyStringRequest request, String vaultId) { + DeidentifyStringRequestV2._FinalStage builder = DeidentifyStringRequestV2.builder().text(request.getText()); + if (request.getConfigurationId() != null) { + builder.configurationId(request.getConfigurationId()); + } + if (request.getConfiguration() != null) { + builder.configuration(toDetectConfig(request.getConfiguration(), vaultId)); + } + return builder.build(); + } + + /** + * Builds the submit request. For file-based requests this reads and base64-encodes the file and infers + * the format from its extension when none was given. + */ + public static DeidentifyFileRequestV2 toDeidentifyFileRequest(DeidentifyFileRequest request, String vaultId) + throws SkyflowException { + String value = request.getValue(); + FileDataFormat format = request.getDataFormat(); + File file = request.getFile(); + if (file != null) { + value = encodeFile(file); + if (format == null) { + format = inferFormat(file.getName()); + } + } + // A local file is always sent as BASE64, whatever dataSource the builder was left with. + DataSourceType dataSource = file != null ? DataSourceType.BASE64 : request.getDataSource(); + DeidentifyFileRequestV2._FinalStage builder = DeidentifyFileRequestV2.builder() + .dataSource(DeidentifyFileRequestV2DataSource.valueOf(dataSource.name())) + .value(value); + if (format != null) { + // The wire value for a file format is the lower-case extension. + builder.dataFormat(DeidentifyFileRequestV2DataFormat.valueOf(format.name().toLowerCase())); + } + if (request.getConfigurationId() != null) { + builder.configurationId(request.getConfigurationId()); + } + if (request.getConfiguration() != null) { + builder.configuration(toDetectConfig(request.getConfiguration(), vaultId)); + } + return builder.build(); + } + + static String encodeFile(File file) throws SkyflowException { + try { + return Base64.getEncoder().encodeToString(Files.readAllBytes(file.toPath())); + } catch (IOException | OutOfMemoryError e) { + LogUtil.printErrorLog(BaseUtils.parameterizedString(ErrorLogs.FAILED_TO_ENCODE_FILE_IN_DEIDENTIFY_FILE.getLog(), "detect")); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.FailedToEncodeFile.getMessage()); + } + } + + /** @return the format matching the file extension, or null when unknown so the server infers it */ + static FileDataFormat inferFormat(String fileName) { + int dot = fileName == null ? -1 : fileName.lastIndexOf('.'); + if (dot < 0 || dot == fileName.length() - 1) { + return null; + } + try { + return FileDataFormat.valueOf(fileName.substring(dot + 1).toUpperCase()); + } catch (IllegalArgumentException unknown) { + return null; + } + } + + public static ReidentifyStringRequestV2 toReidentifyStringRequest(ReidentifyStringRequest request, String vaultId) { + ReidentifyStringRequestV2._FinalStage builder = ReidentifyStringRequestV2.builder() + .vaultId(vaultId) + .text(request.getText()); + if (request.getRedactionLevel() != null) { + builder.redactionLevel(toRedactionLevels(request.getRedactionLevel())); + } + return builder.build(); + } + + public static DetectGuardrailsRequestV2 toCheckGuardrailsRequest(CheckGuardrailsRequest request, String vaultId) { + DetectGuardrailsRequestV2._FinalStage builder = DetectGuardrailsRequestV2.builder() + .text(request.getText()) + .vaultId(vaultId); + if (request.getCheckToxicity() != null) { + builder.checkToxicity(request.getCheckToxicity()); + } + if (request.getDenyTopics() != null) { + builder.denyTopics(request.getDenyTopics()); + } + return builder.build(); + } + + public static DetectConfigV2 toDetectConfig(DetectConfiguration configuration, String vaultId) { + DetectConfigV2._FinalStage builder = DetectConfigV2.builder().vaultId(vaultId); + if (configuration.getName() != null) { + builder.name(configuration.getName()); + } + if (configuration.getDescription() != null) { + builder.description(configuration.getDescription()); + } + if (configuration.getDetect() != null) { + builder.detect(toDetect(configuration.getDetect())); + } + if (configuration.getFileMapping() != null) { + builder.fileMapping(toFileMappings(configuration.getFileMapping())); + } + if (configuration.getMedia() != null) { + builder.media(toMedia(configuration.getMedia())); + } + return builder.build(); + } + + static com.skyflow.generated.detect.rest.types.Detect toDetect(Detect detect) { + com.skyflow.generated.detect.rest.types.Detect.Builder builder = + com.skyflow.generated.detect.rest.types.Detect.builder(); + if (detect.getEntities() != null) { + List entities = new ArrayList<>(); + for (Entity entity : detect.getEntities()) { + if (entity != null) { + entities.add(toEntity(entity)); + } + } + builder.entities(entities); + } + if (detect.getObjectEntities() != null) { + List objectEntities = new ArrayList<>(); + for (ObjectEntity objectEntity : detect.getObjectEntities()) { + if (objectEntity != null) { + objectEntities.add(toObjectEntity(objectEntity)); + } + } + builder.objectEntities(objectEntities); + } + if (detect.getRestrict() != null) { + builder.restrict(detect.getRestrict()); + } + if (detect.getSkip() != null) { + builder.skip(detect.getSkip()); + } + if (detect.getCustomTypes() != null) { + List customTypes = new ArrayList<>(); + for (CustomType customType : detect.getCustomTypes()) { + if (customType != null) { + customTypes.add(toCustomType(customType)); + } + } + builder.customTypes(customTypes); + } + if (detect.getReturnEntities() != null) { + builder.returnEntities(DetectReturnEntities.valueOf(detect.getReturnEntities().name())); + } + return builder.build(); + } + + static DetectEntity toEntity(Entity entity) { + DetectEntity.Builder builder = DetectEntity.builder(); + if (entity.getEntityType() != null) { + builder.entityType(DetectEntityEntityType.valueOf(entity.getEntityType().name())); + } + if (entity.getDeidentificationType() != null) { + builder.deidentificationType(DetectEntityDeidentificationType.valueOf(entity.getDeidentificationType().name())); + } + if (entity.getDestination() != null) { + builder.destination(entity.getDestination()); + } + if (entity.getTransformation() != null) { + builder.transformation(toTransformation(entity.getTransformation())); + } + return builder.build(); + } + + static EntityTransformation toTransformation(Transformation transformation) { + EntityTransformation.Builder builder = EntityTransformation.builder(); + ShiftDates shiftDates = transformation.getShiftDates(); + if (shiftDates != null) { + TransformationShiftDates.Builder shift = TransformationShiftDates.builder(); + if (shiftDates.getMinDays() != null) { + shift.minDays(shiftDates.getMinDays()); + } + if (shiftDates.getMaxDays() != null) { + shift.maxDays(shiftDates.getMaxDays()); + } + builder.shiftDates(shift.build()); + } + return builder.build(); + } + + static DetectCustomTypes toCustomType(CustomType customType) { + DetectCustomTypes.Builder builder = DetectCustomTypes.builder(); + if (customType.getLabel() != null) { + builder.label(customType.getLabel()); + } + if (customType.getMatch() != null) { + builder.match(customType.getMatch()); + } + return builder.build(); + } + + static DetectObjectEntity toObjectEntity(ObjectEntity objectEntity) { + DetectObjectEntity.Builder builder = DetectObjectEntity.builder(); + if (objectEntity.getEntityType() != null) { + builder.entityType(DetectObjectEntityEntityType.valueOf(objectEntity.getEntityType().name())); + } + if (objectEntity.getDeidentificationType() != null) { + builder.deidentificationType( + DetectObjectEntityDeidentificationType.valueOf(objectEntity.getDeidentificationType().name())); + } + return builder.build(); + } + + static List toFileMappings(List fileMappings) { + List result = new ArrayList<>(); + for (FileMapping mapping : fileMappings) { + if (mapping == null) { + continue; + } + com.skyflow.generated.detect.rest.types.FileMapping.Builder builder = + com.skyflow.generated.detect.rest.types.FileMapping.builder(); + if (mapping.getSource() != null) { + builder.source(mapping.getSource()); + } + if (mapping.getDestination() != null) { + builder.destination(mapping.getDestination()); + } + if (mapping.getOutputFileNameSuffix() != null) { + builder.outputFileNameSuffix(mapping.getOutputFileNameSuffix()); + } + if (mapping.getEntitiesDestination() != null) { + builder.entitiesDestination(mapping.getEntitiesDestination()); + } + if (mapping.getObjectEntitiesDestination() != null) { + builder.objectEntitiesDestination(mapping.getObjectEntitiesDestination()); + } + result.add(builder.build()); + } + return result; + } + + static com.skyflow.generated.detect.rest.types.Media toMedia(Media media) { + com.skyflow.generated.detect.rest.types.Media.Builder builder = + com.skyflow.generated.detect.rest.types.Media.builder(); + if (media.getAudio() != null) { + builder.audio(toAudio(media.getAudio())); + } + if (media.getDocument() != null) { + builder.document(toDocument(media.getDocument())); + } + if (media.getImage() != null) { + builder.image(toImage(media.getImage())); + } + return builder.build(); + } + + static AudioV2 toAudio(Audio audio) { + AudioV2.Builder builder = AudioV2.builder(); + if (audio.getOutputProcessedAudio() != null) { + builder.outputProcessedAudio(audio.getOutputProcessedAudio()); + } + if (audio.getOutputTranscription() != null) { + builder.outputTranscription(AudioV2OutputTranscription.valueOf(audio.getOutputTranscription().name())); + } + Bleep bleep = audio.getBleep(); + if (bleep != null) { + AudioV2Bleep.Builder bleepBuilder = AudioV2Bleep.builder(); + if (bleep.getStartPadding() != null) { + bleepBuilder.startPadding(bleep.getStartPadding()); + } + if (bleep.getStopPadding() != null) { + bleepBuilder.stopPadding(bleep.getStopPadding()); + } + if (bleep.getFrequency() != null) { + bleepBuilder.frequency(bleep.getFrequency()); + } + if (bleep.getGain() != null) { + bleepBuilder.gain(bleep.getGain()); + } + builder.bleep(bleepBuilder.build()); + } + return builder.build(); + } + + static DocumentV2 toDocument(Document document) { + DocumentV2.Builder builder = DocumentV2.builder(); + Pdf pdf = document.getPdf(); + if (pdf != null) { + DocumentV2Pdf.Builder pdfBuilder = DocumentV2Pdf.builder(); + if (pdf.getProcessingMode() != null) { + pdfBuilder.processingMode(DocumentV2PdfProcessingMode.valueOf(pdf.getProcessingMode().name())); + } + if (pdf.getDensity() != null) { + pdfBuilder.density(pdf.getDensity()); + } + if (pdf.getMaxResolution() != null) { + pdfBuilder.maxResolution(pdf.getMaxResolution()); + } + builder.pdf(pdfBuilder.build()); + } + return builder.build(); + } + + static ImageV2 toImage(Image image) { + ImageV2.Builder builder = ImageV2.builder(); + if (image.getOutputProcessedImage() != null) { + builder.outputProcessedImage(image.getOutputProcessedImage()); + } + if (image.getOutputOcrText() != null) { + builder.outputOcrText(image.getOutputOcrText()); + } + if (image.getMaskingMethod() != null) { + builder.maskingMethod(ImageV2MaskingMethod.valueOf(image.getMaskingMethod().name())); + } + return builder.build(); + } + + public static List toRedactionLevels(List levels) { + List result = new ArrayList<>(); + for (RedactionLevel level : levels) { + if (level == null) { + continue; + } + com.skyflow.generated.detect.rest.types.RedactionLevel.Builder builder = + com.skyflow.generated.detect.rest.types.RedactionLevel.builder(); + if (level.getEntityName() != null) { + builder.entityName(RedactionLevelEntityName.valueOf(level.getEntityName().name())); + } + if (level.getRedactionType() != null) { + builder.redactionType(RedactionLevelRedactionType.valueOf(level.getRedactionType().name())); + } + if (level.getTokenGroupName() != null) { + builder.tokenGroupName(level.getTokenGroupName()); + } + if (level.getRedactionPattern() != null) { + builder.redactionPattern(level.getRedactionPattern()); + } + result.add(builder.build()); + } + return result; + } +} diff --git a/common/src/main/java/com/skyflow/detect/internal/DetectResponseMapper.java b/common/src/main/java/com/skyflow/detect/internal/DetectResponseMapper.java new file mode 100644 index 00000000..f4d2484b --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/internal/DetectResponseMapper.java @@ -0,0 +1,145 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.CheckGuardrailsResponse; +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DeidentifyFileResponse; +import com.skyflow.detect.DeidentifyStringResponse; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.GuardrailsValidation; +import com.skyflow.detect.DetectedEntity; +import com.skyflow.detect.EntityLocation; +import com.skyflow.detect.Metrics; +import com.skyflow.detect.ReidentifyStringResponse; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2DetectedEntity; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2EntityLocation; +import com.skyflow.generated.detect.rest.types.DetectGuardrailsResponseV2; +import com.skyflow.generated.detect.rest.types.DetectRunsResponseV2; +import com.skyflow.generated.detect.rest.types.ReidentifyStringResponseV2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Converts generated V2 API responses into public SDK response models. Internal to the SDK. + */ +public final class DetectResponseMapper { + private DetectResponseMapper() { + } + + public static DeidentifyStringResponse toDeidentifyStringResponse(DeidentifyStringResponseV2 response) { + List entities = new ArrayList<>(); + List apiEntities = response.getEntities().orElse(null); + if (apiEntities != null) { + for (DeidentifyStringResponseV2DetectedEntity apiEntity : apiEntities) { + if (apiEntity != null) { + entities.add(toDetectedEntity(apiEntity)); + } + } + } + return new DeidentifyStringResponse( + response.getProcessedText().orElse(null), + Collections.unmodifiableList(entities), + response.getMetrics().map(DetectResponseMapper::toMetrics).orElse(null)); + } + + public static ReidentifyStringResponse toReidentifyStringResponse(ReidentifyStringResponseV2 response) { + return new ReidentifyStringResponse( + response.getProcessedText().orElse(null), + response.getMetrics().map(DetectResponseMapper::toMetrics).orElse(null)); + } + + static DetectedEntity toDetectedEntity(DeidentifyStringResponseV2DetectedEntity apiEntity) { + Map scores = apiEntity.getEntityScores().orElse(null); + return new DetectedEntity( + apiEntity.getToken().orElse(null), + apiEntity.getValue().orElse(null), + apiEntity.getLocation().map(DetectResponseMapper::toEntityLocation).orElse(null), + apiEntity.getEntityType().orElse(null), + scores == null ? Collections.emptyMap() : Collections.unmodifiableMap(scores)); + } + + static EntityLocation toEntityLocation(DeidentifyStringResponseV2EntityLocation location) { + return new EntityLocation( + location.getStartIndex().orElse(null), + location.getEndIndex().orElse(null), + location.getStartIndexProcessed().orElse(null), + location.getEndIndexProcessed().orElse(null)); + } + + public static CheckGuardrailsResponse toCheckGuardrailsResponse(DetectGuardrailsResponseV2 response) { + return new CheckGuardrailsResponse( + response.getText(), + enumOrDefault(GuardrailsValidation.class, + response.getValidation() == null ? null : response.getValidation().toString(), GuardrailsValidation.UNKNOWN), + response.getToxic().orElse(null), + response.getDeniedTopic().orElse(null)); + } + + public static GetRunResponse toGetRunResponse(String runId, DetectRunsResponseV2 response) { + List outputs = new ArrayList<>(); + List apiOutputs = response.getOutput().orElse(null); + if (apiOutputs != null) { + for (com.skyflow.generated.detect.rest.types.FileOutput apiOutput : apiOutputs) { + if (apiOutput != null) { + outputs.add(toFileOutput(apiOutput)); + } + } + } + return new GetRunResponse( + runId, + response.getStatus().map(s -> enumOrDefault(DetectRunStatus.class, s.toString(), DetectRunStatus.UNKNOWN)) + .orElse(DetectRunStatus.UNKNOWN), + response.getOutputType().map(t -> enumOrDefault(DataSourceType.class, t.toString(), null)).orElse(null), + Collections.unmodifiableList(outputs), + response.getMetrics().map(DetectResponseMapper::toMetrics).orElse(null), + response.getMessage().orElse(null)); + } + + /** Response for a submit-only call: run id and nothing else. */ + public static DeidentifyFileResponse submittedDeidentifyFileResponse(String runId) { + return new DeidentifyFileResponse(runId, null, null, Collections.emptyList(), null, null); + } + + /** Merges the submit's run id with the polled run. */ + public static DeidentifyFileResponse toDeidentifyFileResponse(String runId, GetRunResponse run) { + return new DeidentifyFileResponse(runId, run.getStatus(), run.getOutputType(), run.getOutput(), + run.getMetrics(), run.getMessage()); + } + + public static FileOutput toFileOutput(com.skyflow.generated.detect.rest.types.FileOutput apiOutput) { + return new FileOutput( + apiOutput.getProcessedFile().orElse(null), + apiOutput.getProcessedFileType().map(Object::toString).orElse(null), + apiOutput.getProcessedFileExtension() + .map(e -> enumOrDefault(FileDataFormat.class, e.toString().toUpperCase(), null)) + .orElse(null)); + } + + /** Maps a wire value onto a public enum, tolerating values this SDK version does not know. */ + static > E enumOrDefault(Class type, String value, E fallback) { + if (value == null) { + return fallback; + } + try { + return Enum.valueOf(type, value); + } catch (IllegalArgumentException unknown) { + return fallback; + } + } + + public static Metrics toMetrics(com.skyflow.generated.detect.rest.types.Metrics metrics) { + return new Metrics( + metrics.getSize().orElse(null), + metrics.getWordCount().orElse(null), + metrics.getCharacterCount().orElse(null), + metrics.getSlides().orElse(null), + metrics.getPages().orElse(null), + metrics.getDuration().orElse(null)); + } +} diff --git a/common/src/main/java/com/skyflow/detect/internal/DetectValidations.java b/common/src/main/java/com/skyflow/detect/internal/DetectValidations.java new file mode 100644 index 00000000..6836dcff --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/internal/DetectValidations.java @@ -0,0 +1,114 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.PollOptions; +import com.skyflow.detect.GetRunRequest; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.utils.BaseUtils; +import com.skyflow.utils.logger.LogUtil; + + +/** + * Client-side validation for Detect V2 requests. Internal to the SDK. + */ +public final class DetectValidations { + static final String INTERFACE_NAME = "detect"; + + private DetectValidations() { + } + + public static void validateDeidentifyStringRequest(DeidentifyStringRequest request) throws SkyflowException { + if (request == null) { + throw invalid(ErrorLogs.DEIDENTIFY_STRING_REQUEST_NULL, BaseErrorMessage.DeidentifyStringRequestNull); + } + if (isBlank(request.getText())) { + throw invalid(ErrorLogs.INVALID_TEXT_IN_DEIDENTIFY_STRING, BaseErrorMessage.InvalidTextInDeidentifyString); + } + // configurationId and configuration are both optional on the API and are passed through as given. + } + + public static void validateDeidentifyFileRequest(DeidentifyFileRequest request) throws SkyflowException { + if (request == null) { + throw invalid(ErrorLogs.DEIDENTIFY_FILE_REQUEST_NULL, BaseErrorMessage.DeidentifyFileRequestNull); + } + if (request.getFile() != null) { + if (!isBlank(request.getValue())) { + throw invalid(ErrorLogs.MULTIPLE_FILE_SOURCES_IN_DEIDENTIFY_FILE, BaseErrorMessage.MultipleFileSourcesInDeidentifyFile); + } + if (!request.getFile().isFile()) { + throw invalid(ErrorLogs.FILE_NOT_FOUND_IN_DEIDENTIFY_FILE, BaseErrorMessage.FileNotFoundToDeidentify); + } + } else { + if (request.getDataSource() == null) { + throw invalid(ErrorLogs.INVALID_DATA_SOURCE_IN_DEIDENTIFY_FILE, BaseErrorMessage.InvalidDataSourceInDeidentifyFile); + } + if (isBlank(request.getValue())) { + throw invalid(ErrorLogs.INVALID_VALUE_IN_DEIDENTIFY_FILE, BaseErrorMessage.InvalidValueInDeidentifyFile); + } + } + // configurationId and configuration are both optional on the API and are passed through as given. + validatePollOptions(request.getPollOptions()); + if (request.getPollOptions() == null && !isBlank(request.getOutputDirectory())) { + throw invalid(ErrorLogs.OUTPUT_DIRECTORY_WITHOUT_POLL_OPTIONS, BaseErrorMessage.OutputDirectoryWithoutPollOptions); + } + } + + static void validatePollOptions(PollOptions options) throws SkyflowException { + if (options == null) { + return; + } + Integer waitTime = options.getWaitTime(); + if (waitTime != null && (waitTime < 1 || waitTime > PollOptions.MAX_WAIT_TIME_SECONDS)) { + throw invalid(ErrorLogs.INVALID_WAIT_TIME_IN_POLL_OPTIONS, BaseErrorMessage.InvalidWaitTimeInPollOptions); + } + Integer maxAttempts = options.getMaxAttempts(); + if (maxAttempts != null && (maxAttempts < 1 || maxAttempts > PollOptions.MAX_MAX_ATTEMPTS)) { + throw invalid(ErrorLogs.INVALID_MAX_ATTEMPTS_IN_POLL_OPTIONS, BaseErrorMessage.InvalidMaxAttemptsInPollOptions); + } + } + + public static void validateReidentifyStringRequest(ReidentifyStringRequest request) throws SkyflowException { + if (request == null) { + throw invalid(ErrorLogs.REIDENTIFY_STRING_REQUEST_NULL, BaseErrorMessage.ReidentifyStringRequestNull); + } + if (isBlank(request.getText())) { + throw invalid(ErrorLogs.INVALID_TEXT_IN_REIDENTIFY_STRING, BaseErrorMessage.InvalidTextInReidentifyString); + } + // redactionLevel entries are optional on the API and are passed through as given. + } + + public static void validateGetRunRequest(GetRunRequest request) throws SkyflowException { + if (request == null) { + throw invalid(ErrorLogs.GET_RUN_REQUEST_NULL, BaseErrorMessage.GetRunRequestNull); + } + if (isBlank(request.getRunId())) { + throw invalid(ErrorLogs.INVALID_RUN_ID_IN_GET_RUN, BaseErrorMessage.InvalidRunIdInGetRun); + } + } + + public static void validateCheckGuardrailsRequest(CheckGuardrailsRequest request) throws SkyflowException { + if (request == null) { + throw invalid(ErrorLogs.CHECK_GUARDRAILS_REQUEST_NULL, BaseErrorMessage.CheckGuardrailsRequestNull); + } + if (isBlank(request.getText())) { + throw invalid(ErrorLogs.INVALID_TEXT_IN_CHECK_GUARDRAILS, BaseErrorMessage.InvalidTextInCheckGuardrails); + } + // checkToxicity and denyTopics are optional on the API and are passed through as given. + } + + + static boolean isBlank(String value) { + return value == null || value.trim().isEmpty(); + } + + private static SkyflowException invalid(ErrorLogs log, BaseErrorMessage message) { + LogUtil.printErrorLog(BaseUtils.parameterizedString(log.getLog(), INTERFACE_NAME)); + return new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), message.getMessage()); + } +} diff --git a/common/src/main/java/com/skyflow/detect/internal/FileOutputWriter.java b/common/src/main/java/com/skyflow/detect/internal/FileOutputWriter.java new file mode 100644 index 00000000..f82f0957 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/internal/FileOutputWriter.java @@ -0,0 +1,118 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.FileOutput; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.BaseConstants; +import com.skyflow.utils.BaseUtils; +import com.skyflow.utils.logger.LogUtil; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Writes the base64 outputs of a successful file run next to, or into a chosen directory for, the + * local file that was submitted. Internal to the SDK. + * + *

Each output becomes {@code processed-.}. Entity outputs carry their + * type in the name so they never collide with a processed file of the same extension: ENTITIES + * becomes {@code processed-entities-.json} and OBJECT_ENTITIES becomes + * {@code processed-object-entities-.json}. If two outputs would still share a name + * the file type is added before the extension. Presigned-URL outputs are not fetched and nothing + * is written for them. + */ +public final class FileOutputWriter { + private static final String ENTITIES_TYPE = "ENTITIES"; + + private FileOutputWriter() { + } + + /** + * @return the files written, in output order; empty when the output type is not BASE64 + * @throws SkyflowException if the directory cannot be created or a file cannot be decoded or written + */ + public static List write(List outputs, DataSourceType outputType, String inputFileName, + String outputDirectory) throws SkyflowException { + List written = new ArrayList<>(); + if (outputs == null || outputs.isEmpty()) { + return written; + } + if (outputType != DataSourceType.BASE64) { + LogUtil.printInfoLog(BaseUtils.parameterizedString(InfoLogs.OUTPUT_NOT_WRITTEN_FOR_OUTPUT_TYPE.getLog(), + String.valueOf(outputType))); + return written; + } + File directory = outputDirectory == null || outputDirectory.trim().isEmpty() ? null : new File(outputDirectory); + if (directory != null && !directory.isDirectory() && !directory.mkdirs()) { + throw writeFailure(ErrorLogs.OUTPUT_DIRECTORY_NOT_CREATED, directory.getPath(), null); + } + String base = stripExtension(inputFileName); + Set used = new HashSet<>(); + for (FileOutput output : outputs) { + if (output == null || output.getProcessedFile() == null) { + continue; + } + String name = fileName(base, output, used); + File target = directory == null ? new File(name) : new File(directory, name); + try { + byte[] bytes = Base64.getDecoder().decode(output.getProcessedFile()); + Files.write(target.toPath(), bytes); + } catch (IllegalArgumentException | IOException e) { + throw writeFailure(ErrorLogs.OUTPUT_FILE_NOT_WRITTEN, target.getPath(), e); + } + LogUtil.printInfoLog(BaseUtils.parameterizedString(InfoLogs.OUTPUT_FILE_WRITTEN.getLog(), target.getPath())); + written.add(target); + } + return written; + } + + /** + * @param base the input file name without its extension + * @return {@code processed-.}, or {@code processed--.json} for entity outputs + */ + static String fileName(String base, FileOutput output, Set used) { + String type = output.getProcessedFileType() == null ? "" : output.getProcessedFileType(); + boolean entities = type.toUpperCase().contains(ENTITIES_TYPE); + String extension; + if (output.getProcessedFileExtension() != null) { + extension = output.getProcessedFileExtension().name().toLowerCase(); + } else if (entities) { + extension = "json"; + } else { + extension = "bin"; + } + // ENTITIES -> processed-entities-, OBJECT_ENTITIES -> processed-object-entities- + String stem = entities + ? BaseConstants.PROCESSED_FILE_NAME_PREFIX + type.toLowerCase().replace('_', '-') + "-" + base + : BaseConstants.PROCESSED_FILE_NAME_PREFIX + base; + String name = stem + "." + extension; + if (!used.add(name)) { + name = stem + "." + (type.isEmpty() ? String.valueOf(used.size()) : type.toLowerCase()) + "." + extension; + used.add(name); + } + return name; + } + + static String stripExtension(String fileName) { + if (fileName == null || fileName.isEmpty()) { + return "output"; + } + int dot = fileName.lastIndexOf('.'); + return dot > 0 ? fileName.substring(0, dot) : fileName; + } + + private static SkyflowException writeFailure(ErrorLogs log, String path, Exception cause) { + LogUtil.printErrorLog(BaseUtils.parameterizedString(log.getLog(), path)); + String message = BaseUtils.parameterizedString(BaseErrorMessage.FailedToWriteOutputFile.getMessage(), path); + return cause == null ? new SkyflowException(message) : new SkyflowException(message, cause); + } +} diff --git a/common/src/main/java/com/skyflow/detect/internal/ReidentifyFileMapper.java b/common/src/main/java/com/skyflow/detect/internal/ReidentifyFileMapper.java new file mode 100644 index 00000000..d1653166 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/internal/ReidentifyFileMapper.java @@ -0,0 +1,69 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.detect.ReidentifyFileResponse; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.ReidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.resources.filesv2.types.ReidentifyFileRequestV2DataFormat; +import com.skyflow.generated.detect.rest.resources.filesv2.types.ReidentifyFileRequestV2DataSource; +import com.skyflow.generated.detect.rest.types.ReidentifyFileResponseV2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Converts the flowvault {@code reidentifyFile} models to and from the generated V2 API types. + * Internal to the SDK. + */ +public final class ReidentifyFileMapper { + private ReidentifyFileMapper() { + } + + public static ReidentifyFileRequestV2 toApiRequest(ReidentifyFileRequest request, String vaultId) { + ReidentifyFileRequestV2._FinalStage builder = ReidentifyFileRequestV2.builder() + .dataSource(ReidentifyFileRequestV2DataSource.valueOf(request.getDataSource().name())) + .value(request.getValue()) + .vaultId(vaultId); + if (request.getDataFormat() != null) { + // The wire value for a file format is the lower-case extension. + builder.dataFormat(ReidentifyFileRequestV2DataFormat.valueOf(request.getDataFormat().name().toLowerCase())); + } + if (request.getRedactionLevel() != null) { + builder.redactionLevel(DetectRequestMapper.toRedactionLevels(request.getRedactionLevel())); + } + return builder.build(); + } + + public static ReidentifyFileResponse toResponse(ReidentifyFileResponseV2 response) { + List outputs = new ArrayList<>(); + List apiOutputs = response.getOutput().orElse(null); + if (apiOutputs != null) { + for (com.skyflow.generated.detect.rest.types.FileOutput apiOutput : apiOutputs) { + if (apiOutput != null) { + outputs.add(DetectResponseMapper.toFileOutput(apiOutput)); + } + } + } + return new ReidentifyFileResponse( + response.getStatus().map(s -> enumOrDefault(DetectRunStatus.class, s.toString(), DetectRunStatus.UNKNOWN)) + .orElse(DetectRunStatus.UNKNOWN), + response.getOutputType().map(t -> enumOrDefault(DataSourceType.class, t.toString(), null)).orElse(null), + Collections.unmodifiableList(outputs), + response.getMetrics().map(DetectResponseMapper::toMetrics).orElse(null)); + } + + /** Maps a wire value onto a public enum, tolerating values this SDK version does not know. */ + private static > E enumOrDefault(Class type, String value, E fallback) { + if (value == null) { + return fallback; + } + try { + return Enum.valueOf(type, value); + } catch (IllegalArgumentException unknown) { + return fallback; + } + } +} diff --git a/common/src/main/java/com/skyflow/detect/internal/ReidentifyFileValidations.java b/common/src/main/java/com/skyflow/detect/internal/ReidentifyFileValidations.java new file mode 100644 index 00000000..46106c96 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/internal/ReidentifyFileValidations.java @@ -0,0 +1,43 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.utils.BaseUtils; +import com.skyflow.utils.logger.LogUtil; + + +/** + * Client-side validation for the flowvault {@code reidentifyFile} request. Internal to the SDK. + */ +public final class ReidentifyFileValidations { + private static final String INTERFACE_NAME = "detect"; + + private ReidentifyFileValidations() { + } + + public static void validateReidentifyFileRequest(ReidentifyFileRequest request) throws SkyflowException { + if (request == null) { + throw invalid(ErrorLogs.REIDENTIFY_FILE_REQUEST_NULL, BaseErrorMessage.ReidentifyFileRequestNull); + } + if (request.getDataSource() == null) { + throw invalid(ErrorLogs.INVALID_DATA_SOURCE_IN_REIDENTIFY_FILE, BaseErrorMessage.InvalidDataSourceInReidentifyFile); + } + if (isBlank(request.getValue())) { + throw invalid(ErrorLogs.INVALID_VALUE_IN_REIDENTIFY_FILE, BaseErrorMessage.InvalidValueInReidentifyFile); + } + // redactionLevel entries are optional on the API and are passed through as given. + } + + + private static boolean isBlank(String value) { + return value == null || value.trim().isEmpty(); + } + + private static SkyflowException invalid(ErrorLogs log, BaseErrorMessage message) { + LogUtil.printErrorLog(BaseUtils.parameterizedString(log.getLog(), INTERFACE_NAME)); + return new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), message.getMessage()); + } +} diff --git a/common/src/main/java/com/skyflow/detect/polling/RunPoller.java b/common/src/main/java/com/skyflow/detect/polling/RunPoller.java new file mode 100644 index 00000000..4aff5a31 --- /dev/null +++ b/common/src/main/java/com/skyflow/detect/polling/RunPoller.java @@ -0,0 +1,99 @@ +package com.skyflow.detect.polling; + +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.PollOptions; +import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.BaseUtils; +import com.skyflow.utils.logger.LogUtil; + +import java.util.Collections; + +/** + * Polls a Detect file run until it reaches a terminal status or the {@link PollOptions} budget is used + * up. Shared by every SDK: the caller supplies how a run is fetched, so each controller plugs in its + * own {@code getRun}. + * + *

Backoff is exponential, 1, 2, 4, 8, 16 then 32 seconds between lookups, with the last sleep + * trimmed so the total never exceeds {@code waitTime}. The first lookup happens immediately after the + * submit. SUCCESS, FAILED and UNKNOWN are terminal; every other status keeps polling. + */ +public final class RunPoller { + /** Longest single pause between two lookups, in seconds. */ + public static final long MAX_DELAY_SECONDS = 32L; + + /** Fetches the current state of a run. */ + public interface RunFetcher { + GetRunResponse fetch(String runId) throws SkyflowException; + } + + /** Pauses the calling thread. Replaceable in tests. */ + public interface Sleeper { + void sleep(long millis) throws InterruptedException; + } + + private RunPoller() { + } + + /** + * Polls on the calling thread. + * + * @param runId run to poll + * @param options wait time and attempt limit, defaults applied + * @param fetcher how to look the run up + * @return the terminal run, or the last non-terminal run seen when the budget ran out or the thread was interrupted + * @throws SkyflowException if a lookup fails + */ + public static GetRunResponse poll(String runId, PollOptions options, RunFetcher fetcher) throws SkyflowException { + return poll(runId, options, fetcher, Thread::sleep); + } + + public static GetRunResponse poll(String runId, PollOptions options, RunFetcher fetcher, Sleeper sleeper) + throws SkyflowException { + int waitTime = options.effectiveWaitTime(); + int maxAttempts = options.effectiveMaxAttempts(); + LogUtil.printInfoLog(BaseUtils.parameterizedString(InfoLogs.POLL_RUN_STARTED.getLog(), runId, + String.valueOf(waitTime), String.valueOf(maxAttempts))); + + long elapsedSeconds = 0; + long delaySeconds = 1; + int attempts = 0; + while (true) { + GetRunResponse run = fetcher.fetch(runId); + attempts++; + if (run == null || run.getStatus() == null) { + // A fetcher that reports nothing is treated as an unknown, terminal state. + run = new GetRunResponse(runId, DetectRunStatus.UNKNOWN, null, Collections.emptyList(), null, null); + } + switch (run.getStatus()) { + case SUCCESS: + case FAILED: + case UNKNOWN: + LogUtil.printInfoLog(BaseUtils.parameterizedString(InfoLogs.POLL_RUN_TERMINAL.getLog(), runId, + run.getStatus().name(), String.valueOf(attempts))); + return run; + default: + // QUEUED, IN_PROGRESS: keep polling while the budget allows. + break; + } + if (attempts >= maxAttempts || elapsedSeconds >= waitTime) { + LogUtil.printInfoLog(BaseUtils.parameterizedString(InfoLogs.POLL_RUN_BUDGET_EXHAUSTED.getLog(), runId, + run.getStatus().name(), String.valueOf(attempts), String.valueOf(elapsedSeconds))); + return run; + } + long sleepSeconds = Math.min(delaySeconds, waitTime - elapsedSeconds); + try { + sleeper.sleep(sleepSeconds * 1000L); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + LogUtil.printInfoLog(BaseUtils.parameterizedString(InfoLogs.POLL_RUN_INTERRUPTED.getLog(), runId, + run.getStatus().name())); + return run; + } + elapsedSeconds += sleepSeconds; + delaySeconds = Math.min(delaySeconds * 2, MAX_DELAY_SECONDS); + } + } +} diff --git a/common/src/main/java/com/skyflow/errors/ErrorMessage.java b/common/src/main/java/com/skyflow/errors/BaseErrorMessage.java similarity index 72% rename from common/src/main/java/com/skyflow/errors/ErrorMessage.java rename to common/src/main/java/com/skyflow/errors/BaseErrorMessage.java index 1e408cca..ff51fb89 100644 --- a/common/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/common/src/main/java/com/skyflow/errors/BaseErrorMessage.java @@ -2,7 +2,12 @@ import com.skyflow.utils.SdkVersion; -public enum ErrorMessage { +/** + * Validation and client-side error messages shared by every SDK. Named {@code BaseErrorMessage} + * rather than {@code ErrorMessage} so it can never be shadowed by a module's own + * {@code com.skyflow.errors.ErrorMessage}: code in common must reference this enum. + */ +public enum BaseErrorMessage { // Client initialization VaultIdAlreadyInConfigList("%s0 Validation error. VaultId is present in an existing config. Specify a new vaultId in config."), VaultIdNotInConfigList("%s0 Validation error. VaultId is missing from the config. Specify the vaultIds from configs."), @@ -12,18 +17,11 @@ public enum ErrorMessage { ConnectionIdNotInConfigList("%s0 Validation error. ConnectionId is missing from the config. Specify the connectionIds from configs."), EmptyCredentials("%s0 Validation error. Invalid credentials. Credentials must not be empty."), NullCredentials("%s0 Validation error. Credentials object is null. Specify a valid Credentials object."), - TableSpecifiedInRequestAndRecordObject("%s0 Validation error. Table name cannot be specified at both the request and record levels. Please specify the table name in only one place."), - UpsertTableRequestAtRecordLevel("%s0 Validation error. Table name should be present at each record level when upsert is present at record level."), - UpsertTableRequestAtRequestLevel("%s0 Validation error. Upsert should be present at each record level when table name is present at record level."), - TableNotSpecifiedInRequestAndRecordObject("%s0 Validation error. Table name is missing. Table name should be specified at one place either at the request level or record level. Please specify the table name at one place."), // Vault config InvalidVaultId("%s0 Initialization failed. Invalid vault ID. Specify a valid vault ID."), EmptyVaultId("%s0 Initialization failed. Invalid vault ID. Vault ID must not be empty."), InvalidClusterId("%s0 Initialization failed. Invalid cluster ID. Specify cluster ID."), EmptyClusterId("%s0 Initialization failed. Invalid cluster ID. Specify a valid cluster ID."), - EmptyVaultUrl("%s0 Initialization failed. Vault URL is empty. Specify a valid vault URL."), - InvalidVaultUrlFormat("%s0 Initialization failed. Vault URL must start with 'https://'."), - EitherVaultUrlOrClusterIdRequired("%s0 Initialization failed. Specify either 'clusterId' or 'vaultURL'."), // Connection config InvalidConnectionId("%s0 Initialization failed. Invalid connection ID. Specify a valid connection ID."), @@ -69,20 +67,11 @@ public enum ErrorMessage { TableKeyError("%s0 Validation error. 'table' key is missing from the payload. Specify a 'table' key."), EmptyTable("%s0 Validation error. 'table' can't be empty. Specify a table."), ValuesKeyError("%s0 Validation error. 'values' key is missing from the payload. Specify a 'values' key."), - EmptyRecords("%s0 Validation error. 'records' can't be empty. Specify records."), - EmptyKeyInRecords("%s0 Validation error. Invalid key in data in records. Specify a valid key."), - EmptyValueInRecords("%s0 Validation error. Invalid value in records. Specify a valid value."), - RecordsKeyError("%s0 Validation error. 'records' key is missing from the payload. Specify a 'records' key."), - EmptyValues("%s0 Validation error. 'values' can't be empty. Specify values."), EmptyKeyInValues("%s0 Validation error. Invalid key in values. Specify a valid key."), - EmptyValueInValues("%s0 Validation error. Invalid value in values. Specify a valid value."), TokensKeyError("%s0 Validation error. 'tokens' key is missing from the payload. Specify a 'tokens' key."), EmptyTokens("%s0 Validation error. The 'tokens' field is empty. Specify tokens for one or more fields."), EmptyKeyInTokens("%s0 Validation error. Invalid key tokens. Specify a valid key."), - EmptyValueInTokens("%s0 Validation error. Invalid value in tokens. Specify a valid value."), EmptyUpsert("%s0 Validation error. 'upsert' key can't be empty. Specify an upsert column."), - InvalidUpsertUpdateType("%s0 Validation error. Invalid upsert updateType. Specify either 'UPDATE' or 'REPLACE'."), - EmptyUpsertValues("%s0 Validation error. Upsert column values can't be empty. Specify at least one upsert column."), HomogenousNotSupportedWithUpsert("%s0 Validation error. 'homogenous' is not supported with 'upsert'. Specify either 'homogenous' or 'upsert'."), TokensPassedForTokenModeDisable("%s0 Validation error. 'tokenMode' wasn't specified. Set 'tokenMode' to 'ENABLE' to insert tokens."), NoTokensWithTokenMode("%s0 Validation error. Tokens weren't specified for records while 'tokenMode' was %s1. Specify tokens."), @@ -90,22 +79,15 @@ public enum ErrorMessage { InsufficientTokensPassedForTokenModeEnableStrict("%s0 Validation error. 'tokenMode' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."), BatchInsertPartialSuccess("%s0 Insert operation completed with partial success."), BatchInsertFailure("%s0 Insert operation failed."), - RecordSizeExceedError("%s0 Maximum number of records exceeded. The limit is 100000."), // Detokenize InvalidDetokenizeData("%s0 Validation error. Invalid detokenize data. Specify valid detokenize data."), EmptyDetokenizeData("%s0 Validation error. Invalid data tokens. Specify at least one data token."), EmptyTokenInDetokenizeData("%s0 Validation error. Invalid data tokens. Specify a valid data token."), - TokensSizeExceedError("%s0 Maximum number of tokens exceeded. The limit is 100000."), // Delete DeleteRequestNull("%s0 Validation error. DeleteRequest object is null. Specify a valid DeleteRequest object."), - // Delete Tokens - DeleteTokensRequestNull("%s0 Validation error. DeleteTokensRequest object is null. Specify a valid DeleteTokensRequest object."), - EmptyDeleteTokensData("%s0 Validation error. Tokens list is empty. Specify at least one token to delete."), - EmptyTokenInDeleteTokensData("%s0 Validation error. Invalid token in delete tokens request. Specify a valid token."), - DeleteTokensSizeExceedError("%s0 Maximum number of tokens exceeded. The limit is 100000."), // Get GetRequestNull("%s0 Validation error. GetRequest object is null. Specify a valid GetRequest object."), @@ -126,15 +108,6 @@ public enum ErrorMessage { ColumnValuesKeyErrorGet("%s0 Validation error. 'columnValues' aren't specified whereas 'columnName' is specified. Either add 'columnValues' or remove 'columnName'."), EmptyColumnValues("%s0 Validation error. 'columnValues' can't be empty. Specify at least one column value"), EmptyValueInColumnValues("%s0 Validation error. Invalid value in column values. Specify a valid column value."), - IdsOrUniqueValuesKeyError("%s0 Validation error. 'ids' or 'uniqueValues' key is missing from the payload. Specify ids or uniqueValues in payload."), - BothIdsAndUniqueValuesSpecified("%s0 Validation error. Both Skyflow IDs and unique values can't be specified. Either specify Skyflow IDs or unique values."), - EmptyUniqueValues("%s0 Validation error. 'uniqueValues' can't be empty. Specify at least one unique value."), - EmptyUniqueValueInUniqueValues("%s0 Validation error. Invalid unique value in 'uniqueValues'. Specify a valid unique value."), - NullColumnRedactions("%s0 Validation error. Column redaction object can not be null. Specify a valid column redaction object."), - NullColumnNameInColumnRedaction("%s0 Validation error. Column name can not be null or empty in column redaction. Specify a valid column name."), - NullRedactionInColumnRedaction("%s0 Validation error. Redaction can not be null or empty in column redaction. Specify a valid redaction."), - BothSingleTableFieldsAndRecordsSpecified("%s0 Validation error. Both single-table lookup fields ('table', 'ids', 'fields', 'uniqueValues', 'columnRedactions') and 'records' can't be specified. Either specify single-table fields or 'records'."), - NullGetRecordRequest("%s0 Validation error. Record in 'records' is null. Specify a valid record."), TokenKeyError("%s0 Validation error. 'token' key is missing from the payload. Specify a 'token' key."), PartialSuccess("%s0 Validation error. Check 'SkyflowError.data' for details."), @@ -146,9 +119,6 @@ public enum ErrorMessage { InvalidSkyflowIdType("%s0 Validation error. Invalid type for 'skyflow_id' in data payload. Specify 'skyflow_id' as a string."), EmptySkyflowId("%s0 Validation error. 'skyflow_id' can't be empty. Specify a skyflow id."), UpdateRequestNull("%s0 Validation error. UpdateRequest object is null. Specify a valid UpdateRequest object."), - UpdateRecordNull("%s0 Validation error. UpdateRequestRecord object in the list is null. Specify a valid UpdateRequestRecord object."), - RecordSkyflowIdKeyError("%s0 Validation error. 'skyflowId' key is missing from the record. Specify a 'skyflowId' key."), - EmptySkyflowIdInRecord("%s0 Validation error. 'skyflowId' can't be empty in the record. Specify a valid skyflow ID."), // Query QueryRequestNull("%s0 Validation error. QueryRequest object is null. Specify a valid QueryRequest object."), @@ -159,15 +129,6 @@ public enum ErrorMessage { ColumnValuesKeyErrorTokenize("%s0 Validation error. 'columnValues' key is missing from the payload. Specify a 'columnValues' key."), EmptyColumnGroupInColumnValue("%s0 Validation error. Invalid column group in column value. Specify a valid column group."), TokenizeRequestNull("%s0 Validation error. TokenizeRequest object is null. Specify a valid TokenizeRequest object."), - EmptyTokenizeData("%s0 Validation error. Tokenize data is empty. Specify at least one tokenize record."), - TokenizeRecordNull("%s0 Validation error. TokenizeRecord in the list is null. Specify a valid TokenizeRecord object."), - InvalidBulkTokenizeRecordType("%s0 Validation error. Record in the list must be of type BulkTokenizeRequestRecord. Specify a valid BulkTokenizeRequestRecord object."), - EmptyValueInTokenizeRecord("%s0 Validation error. Value in TokenizeRecord is null or empty. Specify a valid value."), - EmptyTokenGroupNamesInTokenizeRecord("%s0 Validation error. TokenGroupNames in TokenizeRecord is null or empty. Specify at least one token group name."), - EmptyTokenGroupNameInTokenizeRecord("%s0 Validation error. Token group name in TokenizeRecord is null or empty. Specify a valid token group name."), - TokenizeDataSizeExceedError("%s0 Maximum number of tokenize records exceeded. The limit is 100000."), - MissingIndexInBulkTokenizeRecord("%s0 Validation error. Index in BulkTokenizeRequestRecord is null. Specify an index for every record."), - DuplicateIndexInBulkTokenizeRecord("%s0 Validation error. Duplicate index in BulkTokenizeRequestRecord. Specify a unique index for every record."), // Connection InvalidRequestHeaders("%s0 Validation error. Request headers aren't valid. Specify valid request headers."), @@ -215,17 +176,33 @@ public enum ErrorMessage { DetokenizeRequestNull("%s0 Validation error. DetokenizeRequest object is null. Specify a valid DetokenizeRequest object."), - NullTokenGroupRedactions("%s0 Validation error. TokenGroupRedaction in the list is null. Specify a valid TokenGroupRedactions object."), - NullRedactionInTokenGroup("%s0 Validation error. Redaction in TokenGroupRedactions is null or empty. Specify a valid redaction."), - NullTokenGroupNameInTokenGroup("%s0 Validation error. TokenGroupName in TokenGroupRedactions is null or empty. Specify a valid tokenGroupName."), - InvalidRecord("%s0 Validation error. InsertRecord object in the list is invalid. Specify a valid InsertRecord object."), + // Detect + DeidentifyStringRequestNull("%s0 Validation error. DeidentifyString request cannot be null."), + InvalidTextInDeidentifyString("%s0 Validation error. Invalid text in deidentify string request. Specify a non-empty text."), + ReidentifyStringRequestNull("%s0 Validation error. ReidentifyString request cannot be null."), + InvalidTextInReidentifyString("%s0 Validation error. Invalid text in reidentify string request. Specify a non-empty text."), + DeidentifyFileRequestNull("%s0 Validation error. DeidentifyFile request cannot be null."), + InvalidDataSourceInDeidentifyFile("%s0 Validation error. Invalid dataSource in deidentify file request. Specify BASE64, SKYFLOW_ID or PRESIGNED_URL, or supply a file."), + InvalidValueInDeidentifyFile("%s0 Validation error. Invalid value in deidentify file request. Specify the non-empty base64 content, skyflow id or presigned URL of the file, or supply a file."), + MultipleFileSourcesInDeidentifyFile("%s0 Validation error. Specify either value or file in deidentify file request, not both."), + InvalidWaitTimeInPollOptions("%s0 Validation error. waitTime in pollOptions must be between 1 and 300 seconds."), + InvalidMaxAttemptsInPollOptions("%s0 Validation error. maxAttempts in pollOptions must be between 1 and 23."), + OutputDirectoryWithoutPollOptions("%s0 Validation error. outputDirectory in deidentify file request requires pollOptions."), + FailedToWriteOutputFile("%s0 Failed to write the processed output to %s1."), + GetRunRequestNull("%s0 Validation error. GetRun request cannot be null."), + ReidentifyFileRequestNull("%s0 Validation error. ReidentifyFile request cannot be null."), + InvalidDataSourceInReidentifyFile("%s0 Validation error. Invalid dataSource in reidentify file request. Specify BASE64, SKYFLOW_ID or PRESIGNED_URL."), + InvalidValueInReidentifyFile("%s0 Validation error. Invalid value in reidentify file request. Specify the non-empty base64 content, skyflow id or presigned URL of the file."), + InvalidRunIdInGetRun("%s0 Validation error. Invalid runId in get run request. Specify a non-empty run id."), + CheckGuardrailsRequestNull("%s0 Validation error. CheckGuardrails request cannot be null."), + InvalidTextInCheckGuardrails("%s0 Validation error. Invalid text in check guardrails request. Specify a non-empty text."), ; private final String message; - ErrorMessage(String message) { + BaseErrorMessage(String message) { this.message = message; } diff --git a/common/src/main/java/com/skyflow/errors/SkyflowException.java b/common/src/main/java/com/skyflow/errors/SkyflowException.java index 2b043f92..f8c595ba 100644 --- a/common/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/common/src/main/java/com/skyflow/errors/SkyflowException.java @@ -89,7 +89,7 @@ public SkyflowException(int httpCode, Throwable cause, Map> } catch (Exception e) { this.httpStatus = HttpStatus.BAD_REQUEST.getHttpStatus(); String fullMessage = responseBody != null ? responseBody : - (cause.getLocalizedMessage() != null ? cause.getMessage() : ErrorMessage.ErrorOccurred.getMessage()); + (cause.getLocalizedMessage() != null ? cause.getMessage() : BaseErrorMessage.ErrorOccurred.getMessage()); this.message = fullMessage.split("HTTP response code:")[0].trim(); } } diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientApiException.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientApiException.java new file mode 100644 index 00000000..d864c404 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientApiException.java @@ -0,0 +1,73 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; + +/** + * This exception type will be thrown for any non-2XX API responses. + */ +public class ApiClientApiException extends ApiClientException { + /** + * The error code of the response that triggered the exception. + */ + private final int statusCode; + + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + private final Map> headers; + + public ApiClientApiException(String message, int statusCode, Object body) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.headers = new HashMap<>(); + } + + public ApiClientApiException(String message, int statusCode, Object body, Response rawResponse) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + this.headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); + } + + /** + * @return the statusCode + */ + public int statusCode() { + return this.statusCode; + } + + /** + * @return the body + */ + public Object body() { + return this.body; + } + + /** + * @return the headers + */ + public Map> headers() { + return this.headers; + } + + @Override + public String toString() { + return "ApiClientApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + + ObjectMappers.stringify(body) + "}"; + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientException.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientException.java new file mode 100644 index 00000000..0f99fbc6 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientException.java @@ -0,0 +1,17 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +/** + * This class serves as the base exception for all errors in the SDK. + */ +public class ApiClientException extends RuntimeException { + public ApiClientException(String message) { + super(message); + } + + public ApiClientException(String message, Exception e) { + super(message, e); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientHttpResponse.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientHttpResponse.java new file mode 100644 index 00000000..4b251a98 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/ApiClientHttpResponse.java @@ -0,0 +1,37 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; + +public final class ApiClientHttpResponse { + + private final T body; + + private final Map> headers; + + public ApiClientHttpResponse(T body, Response rawResponse) { + this.body = body; + + Map> headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); + this.headers = headers; + } + + public T body() { + return this.body; + } + + public Map> headers() { + return headers; + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/ClientOptions.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/ClientOptions.java new file mode 100644 index 00000000..cf61d5db --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/ClientOptions.java @@ -0,0 +1,320 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import okhttp3.OkHttpClient; + +public final class ClientOptions { + private final Environment environment; + + private final Map headers; + + private final Map> headerSuppliers; + + private final OkHttpClient httpClient; + + private final boolean ownsHttpClient; + + private final int timeout; + + private final int maxRetries; + + private final Optional initialRetryDelayMillis; + + private final Optional maxRetryDelayMillis; + + private final Optional retryJitterFactor; + + private final Optional logging; + + private ClientOptions( + Environment environment, + Map headers, + Map> headerSuppliers, + OkHttpClient httpClient, + boolean ownsHttpClient, + int timeout, + int maxRetries, + Optional initialRetryDelayMillis, + Optional maxRetryDelayMillis, + Optional retryJitterFactor, + Optional logging) { + this.environment = environment; + this.headers = new HashMap<>(); + this.headers.putAll(headers); + this.headers.putAll(new HashMap() { + { + put("X-Fern-Language", "JAVA"); + put("X-Fern-SDK-Name", "com.skyflow.fern:api-sdk"); + put("X-Fern-SDK-Version", "0.0.98"); + } + }); + this.headerSuppliers = headerSuppliers; + this.httpClient = httpClient; + this.ownsHttpClient = ownsHttpClient; + this.timeout = timeout; + this.maxRetries = maxRetries; + this.initialRetryDelayMillis = initialRetryDelayMillis; + this.maxRetryDelayMillis = maxRetryDelayMillis; + this.retryJitterFactor = retryJitterFactor; + this.logging = logging; + } + + public Environment environment() { + return this.environment; + } + + public Map headers(RequestOptions requestOptions) { + Map values = new HashMap<>(this.headers); + headerSuppliers.forEach((key, supplier) -> { + values.put(key, supplier.get()); + }); + if (requestOptions != null) { + values.putAll(requestOptions.getHeaders()); + } + return values; + } + + public int timeout(RequestOptions requestOptions) { + if (requestOptions == null) { + return this.timeout; + } + return requestOptions.getTimeout().orElse(this.timeout); + } + + public OkHttpClient httpClient() { + return this.httpClient; + } + + public OkHttpClient httpClientWithTimeout(RequestOptions requestOptions) { + if (requestOptions == null) { + return this.httpClient; + } + return this.httpClient + .newBuilder() + .callTimeout(requestOptions.getTimeout().get(), requestOptions.getTimeoutTimeUnit()) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .build(); + } + + public int maxRetries() { + return this.maxRetries; + } + + public Optional initialRetryDelayMillis() { + return this.initialRetryDelayMillis; + } + + public Optional maxRetryDelayMillis() { + return this.maxRetryDelayMillis; + } + + public Optional retryJitterFactor() { + return this.retryJitterFactor; + } + + /** + * Releases resources owned by this client. Only shuts down the underlying OkHttpClient's + * dispatcher executor and evicts its connection pool when this client created that + * OkHttpClient itself; an OkHttpClient supplied via httpClient is left running, since the + * caller owns its lifecycle. + *

+ * In-flight calls are not cancelled or awaited, and any request issued after this method + * returns fails with a {@code RejectedExecutionException}. Options derived from this one via + * {@code Builder.from(...)} share the same dispatcher and connection pool, so closing either + * releases them for both. Calling this method more than once has no further effect. + */ + public void close() { + if (!this.ownsHttpClient) { + return; + } + this.httpClient.dispatcher().executorService().shutdown(); + this.httpClient.connectionPool().evictAll(); + } + + public Optional logging() { + return this.logging; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private Environment environment; + + private final Map headers = new HashMap<>(); + + private final Map> headerSuppliers = new HashMap<>(); + + private int maxRetries = 2; + + private Optional initialRetryDelayMillis = Optional.empty(); + + private Optional maxRetryDelayMillis = Optional.empty(); + + private Optional retryJitterFactor = Optional.empty(); + + private Optional timeout = Optional.empty(); + + private OkHttpClient httpClient = null; + + private boolean ownsHttpClient = true; + + private Optional logging = Optional.empty(); + + public Builder environment(Environment environment) { + this.environment = environment; + return this; + } + + public Builder addHeader(String key, String value) { + if (value != null) { + this.headers.put(key, value); + } + return this; + } + + public Builder addHeader(String key, Supplier value) { + this.headerSuppliers.put(key, value); + return this; + } + + /** + * Override the timeout in seconds. Defaults to 60 seconds. + */ + public Builder timeout(int timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + /** + * Override the timeout in seconds. Defaults to 60 seconds. + */ + public Builder timeout(Optional timeout) { + this.timeout = timeout; + return this; + } + + /** + * Override the maximum number of retries. Defaults to 2 retries. + */ + public Builder maxRetries(int maxRetries) { + this.maxRetries = maxRetries; + return this; + } + + /** + * Override the initial delay (in milliseconds) used for exponential backoff between retries. Defaults to 1000 milliseconds. + */ + public Builder initialRetryDelayMillis(long initialRetryDelayMillis) { + this.initialRetryDelayMillis = Optional.of(initialRetryDelayMillis); + return this; + } + + /** + * Override the maximum delay (in milliseconds) between retries. Defaults to 60000 milliseconds. + */ + public Builder maxRetryDelayMillis(long maxRetryDelayMillis) { + this.maxRetryDelayMillis = Optional.of(maxRetryDelayMillis); + return this; + } + + /** + * Override the jitter factor (between 0 and 1) applied to retry delays. Defaults to 0.2. + */ + public Builder retryJitterFactor(double retryJitterFactor) { + this.retryJitterFactor = Optional.of(retryJitterFactor); + return this; + } + + /** + * Sets the underlying OkHttp client. The caller retains ownership of its lifecycle: + * close() will not shut down its dispatcher executor or evict its connection pool. + */ + public Builder httpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + this.ownsHttpClient = httpClient == null; + return this; + } + + /** + * Configure logging for the SDK. Silent by default — no log output unless explicitly configured. + */ + public Builder logging(LogConfig logging) { + this.logging = Optional.of(logging); + return this; + } + + public ClientOptions build() { + OkHttpClient.Builder httpClientBuilder = + this.httpClient != null ? this.httpClient.newBuilder() : new OkHttpClient.Builder(); + + if (this.httpClient != null) { + timeout.ifPresent(timeout -> httpClientBuilder + .callTimeout(timeout, TimeUnit.SECONDS) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS)); + } else { + httpClientBuilder + .callTimeout(this.timeout.orElse(60), TimeUnit.SECONDS) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .addInterceptor(new RetryInterceptor( + this.maxRetries, + this.initialRetryDelayMillis, + this.maxRetryDelayMillis, + this.retryJitterFactor)); + } + + Logger logger = Logger.from(this.logging); + httpClientBuilder.addInterceptor(new LoggingInterceptor(logger)); + httpClientBuilder.addInterceptor(new ResponseDecompressionInterceptor()); + + this.httpClient = httpClientBuilder.build(); + this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000); + + return new ClientOptions( + environment, + headers, + headerSuppliers, + httpClient, + this.ownsHttpClient, + this.timeout.get(), + this.maxRetries, + this.initialRetryDelayMillis, + this.maxRetryDelayMillis, + this.retryJitterFactor, + this.logging); + } + + /** + * Create a new Builder initialized with values from an existing ClientOptions + */ + public static Builder from(ClientOptions clientOptions) { + Builder builder = new Builder(); + builder.environment = clientOptions.environment(); + builder.timeout = Optional.of(clientOptions.timeout(null)); + builder.httpClient = clientOptions.httpClient(); + builder.ownsHttpClient = clientOptions.ownsHttpClient; + builder.headers.putAll(clientOptions.headers); + builder.headerSuppliers.putAll(clientOptions.headerSuppliers); + builder.maxRetries = clientOptions.maxRetries(); + builder.initialRetryDelayMillis = clientOptions.initialRetryDelayMillis(); + builder.maxRetryDelayMillis = clientOptions.maxRetryDelayMillis(); + builder.retryJitterFactor = clientOptions.retryJitterFactor(); + builder.logging = clientOptions.logging(); + return builder; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/ConsoleLogger.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/ConsoleLogger.java new file mode 100644 index 00000000..e4feb843 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/ConsoleLogger.java @@ -0,0 +1,52 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import java.util.logging.Level; + +/** + * Default logger implementation that writes to the console using {@link java.util.logging.Logger}. + * + *

Uses the "fern" logger name with a simple format of "LEVEL - message". + */ +public final class ConsoleLogger implements ILogger { + + private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("fern"); + + static { + if (logger.getHandlers().length == 0) { + java.util.logging.ConsoleHandler handler = new java.util.logging.ConsoleHandler(); + handler.setFormatter(new java.util.logging.SimpleFormatter() { + @Override + public String format(java.util.logging.LogRecord record) { + return record.getLevel() + " - " + record.getMessage() + System.lineSeparator(); + } + }); + handler.setLevel(Level.ALL); + logger.addHandler(handler); + logger.setUseParentHandlers(false); + logger.setLevel(Level.ALL); + } + } + + @Override + public void debug(String message) { + logger.log(Level.FINE, message); + } + + @Override + public void info(String message) { + logger.log(Level.INFO, message); + } + + @Override + public void warn(String message) { + logger.log(Level.WARNING, message); + } + + @Override + public void error(String message) { + logger.log(Level.SEVERE, message); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/DateTimeDeserializer.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/DateTimeDeserializer.java new file mode 100644 index 00000000..f2c9053a --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/DateTimeDeserializer.java @@ -0,0 +1,70 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.module.SimpleModule; +import java.io.IOException; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.time.temporal.TemporalAccessor; +import java.time.temporal.TemporalQueries; + +/** + * Custom deserializer that handles converting date-time strings into {@link OffsetDateTime} objects. + * Supports ISO 8601 format, space-separated variants, and RFC 1123 (RFC 2822) format. + */ +class DateTimeDeserializer extends JsonDeserializer { + private static final SimpleModule MODULE; + + static { + MODULE = new SimpleModule().addDeserializer(OffsetDateTime.class, new DateTimeDeserializer()); + } + + /** + * Gets a module wrapping this deserializer as an adapter for the Jackson ObjectMapper. + * + * @return A {@link SimpleModule} to be plugged onto Jackson ObjectMapper. + */ + public static SimpleModule getModule() { + return MODULE; + } + + @Override + public OffsetDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { + JsonToken token = parser.currentToken(); + if (token == JsonToken.VALUE_NUMBER_INT) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(parser.getValueAsLong()), ZoneOffset.UTC); + } else { + String value = parser.getValueAsString(); + TemporalAccessor temporal; + try { + temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(value, OffsetDateTime::from, LocalDateTime::from); + } catch (DateTimeParseException e) { + try { + // Fall back to space-separated format (e.g. "2025-02-15 10:30:00+00:00"). + temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest( + value.replace(' ', 'T'), OffsetDateTime::from, LocalDateTime::from); + } catch (DateTimeParseException e2) { + // Fall back to RFC 1123 format (e.g. "Thu, 07 May 2026 14:23:38 +0000"). + temporal = DateTimeFormatter.RFC_1123_DATE_TIME.parseBest( + value, OffsetDateTime::from, LocalDateTime::from); + } + } + + if (temporal.query(TemporalQueries.offset()) == null) { + return LocalDateTime.from(temporal).atOffset(ZoneOffset.UTC); + } else { + return OffsetDateTime.from(temporal); + } + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/DoubleSerializer.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/DoubleSerializer.java new file mode 100644 index 00000000..635869a6 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/DoubleSerializer.java @@ -0,0 +1,43 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; +import java.io.IOException; + +/** + * Custom serializer that writes integer-valued doubles without a decimal point. + * For example, {@code 24000.0} is serialized as {@code 24000} instead of {@code 24000.0}. + * Non-integer values like {@code 3.14} are serialized normally. + */ +class DoubleSerializer extends JsonSerializer { + private static final SimpleModule MODULE; + + static { + MODULE = new SimpleModule() + .addSerializer(Double.class, new DoubleSerializer()) + .addSerializer(double.class, new DoubleSerializer()); + } + + /** + * Gets a module wrapping this serializer as an adapter for the Jackson ObjectMapper. + * + * @return A {@link SimpleModule} to be plugged onto Jackson ObjectMapper. + */ + public static SimpleModule getModule() { + return MODULE; + } + + @Override + public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + if (value != null && value == Math.floor(value) && !Double.isInfinite(value) && !Double.isNaN(value)) { + gen.writeNumber(value.longValue()); + } else { + gen.writeNumber(value); + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/Environment.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/Environment.java new file mode 100644 index 00000000..c95311b0 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/Environment.java @@ -0,0 +1,25 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +public final class Environment { + public static final Environment PRODUCTION = new Environment("https://%7B%7BvaultUri%7D%7D.vault.skyflowapis.com"); + + public static final Environment SANDBOX = + new Environment("https://%7B%7BvaultUri%7D%7D.vault.skyflowapis-preview.com"); + + private final String url; + + private Environment(String url) { + this.url = url; + } + + public String getUrl() { + return this.url; + } + + public static Environment custom(String url) { + return new Environment(url); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/ILogger.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/ILogger.java new file mode 100644 index 00000000..0df7a4f5 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/ILogger.java @@ -0,0 +1,38 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +/** + * Interface for custom logger implementations. + * + *

Implement this interface to provide a custom logging backend for the SDK. + * The SDK will call the appropriate method based on the log level. + * + *

Example: + *

{@code
+ * public class MyCustomLogger implements ILogger {
+ *     public void debug(String message) {
+ *         System.out.println("[DBG] " + message);
+ *     }
+ *     public void info(String message) {
+ *         System.out.println("[INF] " + message);
+ *     }
+ *     public void warn(String message) {
+ *         System.out.println("[WRN] " + message);
+ *     }
+ *     public void error(String message) {
+ *         System.out.println("[ERR] " + message);
+ *     }
+ * }
+ * }
+ */ +public interface ILogger { + void debug(String message); + + void info(String message); + + void warn(String message); + + void error(String message); +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/LogConfig.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/LogConfig.java new file mode 100644 index 00000000..e613616b --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/LogConfig.java @@ -0,0 +1,98 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +/** + * Configuration for SDK logging. + * + *

Use the builder to configure logging behavior: + *

{@code
+ * LogConfig config = LogConfig.builder()
+ *     .level(LogLevel.DEBUG)
+ *     .silent(false)
+ *     .build();
+ * }
+ * + *

Or with a custom logger: + *

{@code
+ * LogConfig config = LogConfig.builder()
+ *     .level(LogLevel.DEBUG)
+ *     .logger(new MyCustomLogger())
+ *     .silent(false)
+ *     .build();
+ * }
+ * + *

Defaults: + *

    + *
  • {@code level} — {@link LogLevel#INFO}
  • + *
  • {@code logger} — {@link ConsoleLogger} (writes to stderr via java.util.logging)
  • + *
  • {@code silent} — {@code true} (no output unless explicitly enabled)
  • + *
+ */ +public final class LogConfig { + + private final LogLevel level; + private final ILogger logger; + private final boolean silent; + + private LogConfig(LogLevel level, ILogger logger, boolean silent) { + this.level = level; + this.logger = logger; + this.silent = silent; + } + + public LogLevel level() { + return level; + } + + public ILogger logger() { + return logger; + } + + public boolean silent() { + return silent; + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private LogLevel level = LogLevel.INFO; + private ILogger logger = new ConsoleLogger(); + private boolean silent = true; + + private Builder() {} + + /** + * Set the minimum log level. Only messages at this level or above will be logged. + * Defaults to {@link LogLevel#INFO}. + */ + public Builder level(LogLevel level) { + this.level = level; + return this; + } + + /** + * Set a custom logger implementation. Defaults to {@link ConsoleLogger}. + */ + public Builder logger(ILogger logger) { + this.logger = logger; + return this; + } + + /** + * Set whether logging is silent (disabled). Defaults to {@code true}. + * Set to {@code false} to enable log output. + */ + public Builder silent(boolean silent) { + this.silent = silent; + return this; + } + + public LogConfig build() { + return new LogConfig(level, logger, silent); + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/LogLevel.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/LogLevel.java new file mode 100644 index 00000000..b37806c0 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/LogLevel.java @@ -0,0 +1,36 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +/** + * Log levels for SDK logging configuration. + * Silent by default — no log output unless explicitly configured. + */ +public enum LogLevel { + DEBUG(1), + INFO(2), + WARN(3), + ERROR(4); + + private final int value; + + LogLevel(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + /** + * Parse a log level from a string (case-insensitive). + * + * @param level the level string (debug, info, warn, error) + * @return the corresponding LogLevel + * @throws IllegalArgumentException if the string does not match any level + */ + public static LogLevel fromString(String level) { + return LogLevel.valueOf(level.toUpperCase()); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/Logger.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/Logger.java new file mode 100644 index 00000000..19a9d1fe --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/Logger.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +/** + * SDK logger that filters messages based on level and silent mode. + * + *

Silent by default — no log output unless explicitly configured. + * Create via {@link LogConfig} or directly: + *

{@code
+ * Logger logger = new Logger(LogLevel.DEBUG, new ConsoleLogger(), false);
+ * logger.debug("request sent");
+ * }
+ */ +public final class Logger { + + private static final Logger DEFAULT = new Logger(LogLevel.INFO, new ConsoleLogger(), true); + + private final LogLevel level; + private final ILogger logger; + private final boolean silent; + + public Logger(LogLevel level, ILogger logger, boolean silent) { + this.level = level; + this.logger = logger; + this.silent = silent; + } + + /** + * Returns a default silent logger (no output). + */ + public static Logger getDefault() { + return DEFAULT; + } + + /** + * Creates a Logger from a {@link LogConfig}. If config is {@code null}, returns the default silent logger. + */ + public static Logger from(LogConfig config) { + if (config == null) { + return DEFAULT; + } + return new Logger(config.level(), config.logger(), config.silent()); + } + + /** + * Creates a Logger from an {@code Optional}. If empty, returns the default silent logger. + */ + public static Logger from(java.util.Optional config) { + return config.map(Logger::from).orElse(DEFAULT); + } + + private boolean shouldLog(LogLevel messageLevel) { + return !silent && level.getValue() <= messageLevel.getValue(); + } + + public boolean isDebug() { + return shouldLog(LogLevel.DEBUG); + } + + public boolean isInfo() { + return shouldLog(LogLevel.INFO); + } + + public boolean isWarn() { + return shouldLog(LogLevel.WARN); + } + + public boolean isError() { + return shouldLog(LogLevel.ERROR); + } + + public void debug(String message) { + if (isDebug()) { + logger.debug(message); + } + } + + public void info(String message) { + if (isInfo()) { + logger.info(message); + } + } + + public void warn(String message) { + if (isWarn()) { + logger.warn(message); + } + } + + public void error(String message) { + if (isError()) { + logger.error(message); + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/LoggingInterceptor.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/LoggingInterceptor.java new file mode 100644 index 00000000..33c1d6aa --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/LoggingInterceptor.java @@ -0,0 +1,104 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +/** + * OkHttp interceptor that logs HTTP requests and responses. + * + *

Logs request method, URL, and headers (with sensitive values redacted) at debug level. + * Logs response status at debug level, and 4xx/5xx responses at error level. + * Does nothing if the logger is silent. + */ +public final class LoggingInterceptor implements Interceptor { + + private static final Set SENSITIVE_HEADERS = new HashSet<>(Arrays.asList( + "authorization", + "www-authenticate", + "x-api-key", + "api-key", + "apikey", + "x-api-token", + "x-auth-token", + "auth-token", + "proxy-authenticate", + "proxy-authorization", + "cookie", + "set-cookie", + "x-csrf-token", + "x-xsrf-token", + "x-session-token", + "x-access-token")); + + private final Logger logger; + + public LoggingInterceptor(Logger logger) { + this.logger = logger; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + if (logger.isDebug()) { + StringBuilder sb = new StringBuilder(); + sb.append("HTTP Request: ").append(request.method()).append(" ").append(request.url()); + sb.append(" headers={"); + boolean first = true; + for (String name : request.headers().names()) { + if (!first) { + sb.append(", "); + } + sb.append(name).append("="); + if (SENSITIVE_HEADERS.contains(name.toLowerCase())) { + sb.append("[REDACTED]"); + } else { + sb.append(request.header(name)); + } + first = false; + } + sb.append("}"); + sb.append(" has_body=").append(request.body() != null); + logger.debug(sb.toString()); + } + + Response response = chain.proceed(request); + + if (logger.isDebug()) { + StringBuilder sb = new StringBuilder(); + sb.append("HTTP Response: status=").append(response.code()); + sb.append(" url=").append(response.request().url()); + sb.append(" headers={"); + boolean first = true; + for (String name : response.headers().names()) { + if (!first) { + sb.append(", "); + } + sb.append(name).append("="); + if (SENSITIVE_HEADERS.contains(name.toLowerCase())) { + sb.append("[REDACTED]"); + } else { + sb.append(response.header(name)); + } + first = false; + } + sb.append("}"); + logger.debug(sb.toString()); + } + + if (response.code() >= 400 && logger.isError()) { + logger.error("HTTP Error: status=" + response.code() + " url=" + + response.request().url()); + } + + return response; + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/MediaTypes.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/MediaTypes.java new file mode 100644 index 00000000..b2d084be --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/MediaTypes.java @@ -0,0 +1,13 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import okhttp3.MediaType; + +public final class MediaTypes { + + public static final MediaType APPLICATION_JSON = MediaType.parse("application/json"); + + private MediaTypes() {} +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/ObjectMappers.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/ObjectMappers.java new file mode 100644 index 00000000..7b4660ad --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/ObjectMappers.java @@ -0,0 +1,46 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.io.IOException; + +public final class ObjectMappers { + public static final ObjectMapper JSON_MAPPER = JsonMapper.builder() + .addModule(new Jdk8Module()) + .addModule(new JavaTimeModule()) + .addModule(DateTimeDeserializer.getModule()) + .addModule(DoubleSerializer.getModule()) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .build(); + + private ObjectMappers() {} + + public static String stringify(Object o) { + try { + return JSON_MAPPER + .setSerializationInclusion(JsonInclude.Include.ALWAYS) + .writerWithDefaultPrettyPrinter() + .writeValueAsString(o); + } catch (IOException e) { + return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); + } + } + + public static Object parseErrorBody(String responseBodyString) { + try { + return JSON_MAPPER.readValue(responseBodyString, Object.class); + } catch (JsonProcessingException ignored) { + return responseBodyString; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/QueryStringMapper.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/QueryStringMapper.java new file mode 100644 index 00000000..ba2dadc4 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/QueryStringMapper.java @@ -0,0 +1,142 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import okhttp3.HttpUrl; +import okhttp3.MultipartBody; + +public class QueryStringMapper { + + private static final ObjectMapper MAPPER = ObjectMappers.JSON_MAPPER; + + public static void addQueryParameter(HttpUrl.Builder httpUrl, String key, Object value, boolean arraysAsRepeats) { + JsonNode valueNode = MAPPER.valueToTree(value); + + List> flat; + if (valueNode.isObject()) { + flat = flattenObject((ObjectNode) valueNode, arraysAsRepeats); + } else if (valueNode.isArray()) { + flat = flattenArray((ArrayNode) valueNode, "", arraysAsRepeats); + } else { + if (valueNode.isTextual()) { + httpUrl.addQueryParameter(key, valueNode.textValue()); + } else { + httpUrl.addQueryParameter(key, valueNode.toString()); + } + return; + } + + for (Map.Entry field : flat) { + if (field.getValue().isTextual()) { + httpUrl.addQueryParameter(key + field.getKey(), field.getValue().textValue()); + } else { + httpUrl.addQueryParameter(key + field.getKey(), field.getValue().toString()); + } + } + } + + public static void addFormDataPart( + MultipartBody.Builder multipartBody, String key, Object value, boolean arraysAsRepeats) { + JsonNode valueNode = MAPPER.valueToTree(value); + + List> flat; + if (valueNode.isObject()) { + flat = flattenObject((ObjectNode) valueNode, arraysAsRepeats); + } else if (valueNode.isArray()) { + flat = flattenArray((ArrayNode) valueNode, "", arraysAsRepeats); + } else { + if (valueNode.isTextual()) { + multipartBody.addFormDataPart(key, valueNode.textValue()); + } else { + multipartBody.addFormDataPart(key, valueNode.toString()); + } + return; + } + + for (Map.Entry field : flat) { + if (field.getValue().isTextual()) { + multipartBody.addFormDataPart( + key + field.getKey(), field.getValue().textValue()); + } else { + multipartBody.addFormDataPart( + key + field.getKey(), field.getValue().toString()); + } + } + } + + public static List> flattenObject(ObjectNode object, boolean arraysAsRepeats) { + List> flat = new ArrayList<>(); + + Iterator> fields = object.fields(); + while (fields.hasNext()) { + Map.Entry field = fields.next(); + + String key = "[" + field.getKey() + "]"; + + if (field.getValue().isObject()) { + List> flatField = + flattenObject((ObjectNode) field.getValue(), arraysAsRepeats); + addAll(flat, flatField, key); + } else if (field.getValue().isArray()) { + List> flatField = + flattenArray((ArrayNode) field.getValue(), key, arraysAsRepeats); + addAll(flat, flatField, ""); + } else { + flat.add(new AbstractMap.SimpleEntry<>(key, field.getValue())); + } + } + + return flat; + } + + private static List> flattenArray( + ArrayNode array, String key, boolean arraysAsRepeats) { + List> flat = new ArrayList<>(); + + Iterator elements = array.elements(); + + int index = 0; + while (elements.hasNext()) { + JsonNode element = elements.next(); + + String indexKey = key + "[" + index + "]"; + + if (arraysAsRepeats) { + indexKey = key; + } + + if (element.isObject()) { + List> flatField = flattenObject((ObjectNode) element, arraysAsRepeats); + addAll(flat, flatField, indexKey); + } else if (element.isArray()) { + List> flatField = flattenArray((ArrayNode) element, "", arraysAsRepeats); + addAll(flat, flatField, indexKey); + } else { + flat.add(new AbstractMap.SimpleEntry<>(indexKey, element)); + } + + index++; + } + + return flat; + } + + private static void addAll( + List> target, List> source, String prefix) { + for (Map.Entry entry : source) { + Map.Entry entryToAdd = + new AbstractMap.SimpleEntry<>(prefix + entry.getKey(), entry.getValue()); + target.add(entryToAdd); + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/RequestOptions.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/RequestOptions.java new file mode 100644 index 00000000..7f5ccea0 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/RequestOptions.java @@ -0,0 +1,154 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +public final class RequestOptions { + private final String token; + + private final Optional timeout; + + private final TimeUnit timeoutTimeUnit; + + private final Optional maxRetries; + + private final Map headers; + + private final Map> headerSuppliers; + + private final Map queryParameters; + + private final Map> queryParameterSuppliers; + + private RequestOptions( + String token, + Optional timeout, + TimeUnit timeoutTimeUnit, + Optional maxRetries, + Map headers, + Map> headerSuppliers, + Map queryParameters, + Map> queryParameterSuppliers) { + this.token = token; + this.timeout = timeout; + this.timeoutTimeUnit = timeoutTimeUnit; + this.maxRetries = maxRetries; + this.headers = headers; + this.headerSuppliers = headerSuppliers; + this.queryParameters = queryParameters; + this.queryParameterSuppliers = queryParameterSuppliers; + } + + public Optional getTimeout() { + return timeout; + } + + public TimeUnit getTimeoutTimeUnit() { + return timeoutTimeUnit; + } + + public Optional getMaxRetries() { + return maxRetries; + } + + public Map getHeaders() { + Map headers = new HashMap<>(); + if (this.token != null) { + headers.put("Authorization", "Bearer " + this.token); + } + headers.putAll(this.headers); + this.headerSuppliers.forEach((key, supplier) -> { + headers.put(key, supplier.get()); + }); + return headers; + } + + public Map getQueryParameters() { + Map queryParameters = new HashMap<>(this.queryParameters); + this.queryParameterSuppliers.forEach((key, supplier) -> { + queryParameters.put(key, supplier.get()); + }); + return queryParameters; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private String token = null; + + private Optional timeout = Optional.empty(); + + private TimeUnit timeoutTimeUnit = TimeUnit.SECONDS; + + private Optional maxRetries = Optional.empty(); + + private final Map headers = new HashMap<>(); + + private final Map> headerSuppliers = new HashMap<>(); + + private final Map queryParameters = new HashMap<>(); + + private final Map> queryParameterSuppliers = new HashMap<>(); + + public Builder token(String token) { + this.token = token; + return this; + } + + public Builder timeout(Integer timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + public Builder timeout(Integer timeout, TimeUnit timeoutTimeUnit) { + this.timeout = Optional.of(timeout); + this.timeoutTimeUnit = timeoutTimeUnit; + return this; + } + + public Builder maxRetries(Integer maxRetries) { + this.maxRetries = Optional.of(maxRetries); + return this; + } + + public Builder addHeader(String key, String value) { + this.headers.put(key, value); + return this; + } + + public Builder addHeader(String key, Supplier value) { + this.headerSuppliers.put(key, value); + return this; + } + + public Builder addQueryParameter(String key, String value) { + this.queryParameters.put(key, value); + return this; + } + + public Builder addQueryParameter(String key, Supplier value) { + this.queryParameterSuppliers.put(key, value); + return this; + } + + public RequestOptions build() { + return new RequestOptions( + token, + timeout, + timeoutTimeUnit, + maxRetries, + headers, + headerSuppliers, + queryParameters, + queryParameterSuppliers); + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/ResponseDecompressionInterceptor.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/ResponseDecompressionInterceptor.java new file mode 100644 index 00000000..9988a7fc --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/ResponseDecompressionInterceptor.java @@ -0,0 +1,56 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import java.io.IOException; +import java.util.zip.Inflater; +import okhttp3.Interceptor; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okio.GzipSource; +import okio.InflaterSource; +import okio.Okio; +import okio.Source; + +/** + * Decompresses gzip and deflate encoded response bodies. OkHttp only performs + * transparent decompression when it adds the Accept-Encoding header itself, so + * responses to requests with an explicitly set Accept-Encoding header would + * otherwise be returned as raw compressed bytes. + */ +public class ResponseDecompressionInterceptor implements Interceptor { + + @Override + public Response intercept(Chain chain) throws IOException { + return decompress(chain.proceed(chain.request())); + } + + private Response decompress(Response response) { + ResponseBody body = response.body(); + if (body == null) { + return response; + } + String encoding = response.header("Content-Encoding"); + if (encoding == null) { + return response; + } + Source decompressedSource; + if (encoding.equalsIgnoreCase("gzip") || encoding.equalsIgnoreCase("x-gzip")) { + decompressedSource = new GzipSource(body.source()); + } else if (encoding.equalsIgnoreCase("deflate")) { + decompressedSource = new InflaterSource(body.source(), new Inflater()); + } else { + return response; + } + ResponseBody decompressedBody = ResponseBody.create(body.contentType(), -1L, Okio.buffer(decompressedSource)); + return response.newBuilder() + .headers(response.headers() + .newBuilder() + .removeAll("Content-Encoding") + .removeAll("Content-Length") + .build()) + .body(decompressedBody) + .build(); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/core/RetryInterceptor.java b/common/src/main/java/com/skyflow/generated/detect/rest/core/RetryInterceptor.java new file mode 100644 index 00000000..c46a526e --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/core/RetryInterceptor.java @@ -0,0 +1,242 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.core; + +import java.io.IOException; +import java.time.Duration; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Optional; +import java.util.Random; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +public class RetryInterceptor implements Interceptor { + + private static final Duration DEFAULT_INITIAL_RETRY_DELAY = Duration.ofMillis(1000); + private static final Duration DEFAULT_MAX_RETRY_DELAY = Duration.ofMillis(60000); + private static final double DEFAULT_JITTER_FACTOR = 0.2; + + private final int maxRetries; + private final Duration initialRetryDelay; + private final Duration maxRetryDelay; + private final double jitterFactor; + private final Random random = new Random(); + + public RetryInterceptor(int maxRetries) { + this(maxRetries, Optional.empty(), Optional.empty(), Optional.empty()); + } + + public RetryInterceptor( + int maxRetries, + Optional initialRetryDelayMillis, + Optional maxRetryDelayMillis, + Optional jitterFactor) { + initialRetryDelayMillis.ifPresent(delay -> { + if (delay < 0) { + throw new IllegalArgumentException("initialRetryDelayMillis must be non-negative"); + } + }); + maxRetryDelayMillis.ifPresent(delay -> { + if (delay < 0) { + throw new IllegalArgumentException("maxRetryDelayMillis must be non-negative"); + } + }); + jitterFactor.ifPresent(factor -> { + if (factor < 0 || factor > 1) { + throw new IllegalArgumentException("jitterFactor must be between 0 and 1"); + } + }); + this.maxRetries = maxRetries; + this.initialRetryDelay = initialRetryDelayMillis.map(Duration::ofMillis).orElse(DEFAULT_INITIAL_RETRY_DELAY); + this.maxRetryDelay = maxRetryDelayMillis.map(Duration::ofMillis).orElse(DEFAULT_MAX_RETRY_DELAY); + this.jitterFactor = jitterFactor.orElse(DEFAULT_JITTER_FACTOR); + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + int effectiveMaxRetries = resolveMaxRetries(request); + Response response = chain.proceed(request); + + if (shouldRetry(response.code())) { + return retryChain(response, chain, effectiveMaxRetries); + } + + return response; + } + + private int resolveMaxRetries(Request request) { + MaxRetriesOverride override = request.tag(MaxRetriesOverride.class); + return override != null ? override.getValue() : this.maxRetries; + } + + private Response retryChain(Response response, Chain chain, int maxRetries) throws IOException { + ExponentialBackoff backoff = new ExponentialBackoff(maxRetries); + Optional nextBackoff = backoff.nextBackoff(response); + while (nextBackoff.isPresent()) { + try { + Thread.sleep(nextBackoff.get().toMillis()); + } catch (InterruptedException e) { + throw new IOException("Interrupted while trying request", e); + } + response.close(); + response = chain.proceed(chain.request()); + if (shouldRetry(response.code())) { + nextBackoff = backoff.nextBackoff(response); + } else { + return response; + } + } + + return response; + } + + /** + * Calculates the retry delay from response headers, with fallback to exponential backoff. + * Priority: Retry-After > X-RateLimit-Reset > Exponential Backoff + */ + private Duration getRetryDelayFromHeaders(Response response, int retryAttempt) { + // Check for Retry-After header first (RFC 7231), with no jitter + String retryAfter = response.header("Retry-After"); + if (retryAfter != null) { + // Parse as number of seconds... + Optional secondsDelay = tryParseLong(retryAfter) + .map(seconds -> seconds * 1000) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, maxRetryDelay.toMillis())) + .map(Duration::ofMillis); + if (secondsDelay.isPresent()) { + return secondsDelay.get(); + } + + // ...or as an HTTP date; both are valid + Optional dateDelay = tryParseHttpDate(retryAfter) + .map(resetTime -> resetTime.toInstant().toEpochMilli() - System.currentTimeMillis()) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, maxRetryDelay.toMillis())) + .map(Duration::ofMillis); + if (dateDelay.isPresent()) { + return dateDelay.get(); + } + } + + // Then check for industry-standard X-RateLimit-Reset header, with positive jitter + String rateLimitReset = response.header("X-RateLimit-Reset"); + if (rateLimitReset != null) { + // Assume Unix timestamp in epoch seconds + Optional rateLimitDelay = tryParseLong(rateLimitReset) + .map(resetTimeSeconds -> (resetTimeSeconds * 1000) - System.currentTimeMillis()) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, maxRetryDelay.toMillis())) + .map(this::addPositiveJitter) + .map(Duration::ofMillis); + if (rateLimitDelay.isPresent()) { + return rateLimitDelay.get(); + } + } + + // Fall back to exponential backoff, with symmetric jitter + long initialDelayMillis = initialRetryDelay.toMillis(); + long maxDelayMillis = maxRetryDelay.toMillis(); + long cappedDelay; + if (retryAttempt >= Long.SIZE - 1 || initialDelayMillis > (maxDelayMillis >> retryAttempt)) { + // initialDelayMillis * 2^retryAttempt would exceed maxDelayMillis (or overflow) + cappedDelay = maxDelayMillis; + } else { + cappedDelay = Math.min(initialDelayMillis << retryAttempt, maxDelayMillis); // 2^retryAttempt + } + return Duration.ofMillis(addSymmetricJitter(cappedDelay)); + } + + /** + * Attempts to parse a string as a long, returning empty Optional on failure. + */ + private Optional tryParseLong(String value) { + if (value == null) { + return Optional.empty(); + } + try { + return Optional.of(Long.parseLong(value)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + /** + * Attempts to parse a string as an HTTP date (RFC 1123), returning empty Optional on failure. + */ + private Optional tryParseHttpDate(String value) { + if (value == null) { + return Optional.empty(); + } + try { + return Optional.of(ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME)); + } catch (DateTimeParseException e) { + return Optional.empty(); + } + } + + /** + * Adds positive jitter (100-120% of original value) to prevent thundering herd. + * Used for X-RateLimit-Reset header delays. + */ + private long addPositiveJitter(long delayMs) { + double jitterMultiplier = 1.0 + (random.nextDouble() * jitterFactor); + return (long) (delayMs * jitterMultiplier); + } + + /** + * Adds symmetric jitter (90-110% of original value) to prevent thundering herd. + * Used for exponential backoff delays. + */ + private long addSymmetricJitter(long delayMs) { + double jitterMultiplier = 1.0 + ((random.nextDouble() - 0.5) * jitterFactor); + return (long) (delayMs * jitterMultiplier); + } + + private static boolean shouldRetry(int statusCode) { + return statusCode == 408 || statusCode == 429 || statusCode >= 500; + } + + /** + * Per-request override carried on the OkHttp {@link Request} as a tag. + * When present, the interceptor uses this value instead of the client-wide + * {@code maxRetries} configured at construction time. + */ + public static final class MaxRetriesOverride { + private final int value; + + public MaxRetriesOverride(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + + private final class ExponentialBackoff { + + private final int maxNumRetries; + + private int retryNumber = 0; + + ExponentialBackoff(int maxNumRetries) { + this.maxNumRetries = maxNumRetries; + } + + public Optional nextBackoff(Response response) { + if (retryNumber >= maxNumRetries) { + return Optional.empty(); + } + + Duration delay = getRetryDelayFromHeaders(response, retryNumber); + retryNumber += 1; + return Optional.of(delay); + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/errors/BadRequestError.java b/common/src/main/java/com/skyflow/generated/detect/rest/errors/BadRequestError.java new file mode 100644 index 00000000..7858ef63 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/errors/BadRequestError.java @@ -0,0 +1,33 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.errors; + +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.types.ErrorResponse; +import okhttp3.Response; + +public final class BadRequestError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final ErrorResponse body; + + public BadRequestError(ErrorResponse body) { + super("BadRequestError", 400, body); + this.body = body; + } + + public BadRequestError(ErrorResponse body, Response rawResponse) { + super("BadRequestError", 400, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public ErrorResponse body() { + return this.body; + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/errors/InternalServerError.java b/common/src/main/java/com/skyflow/generated/detect/rest/errors/InternalServerError.java new file mode 100644 index 00000000..c21d7766 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/errors/InternalServerError.java @@ -0,0 +1,33 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.errors; + +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.types.ErrorResponse; +import okhttp3.Response; + +public final class InternalServerError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final ErrorResponse body; + + public InternalServerError(ErrorResponse body) { + super("InternalServerError", 500, body); + this.body = body; + } + + public InternalServerError(ErrorResponse body, Response rawResponse) { + super("InternalServerError", 500, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public ErrorResponse body() { + return this.body; + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/errors/UnauthorizedError.java b/common/src/main/java/com/skyflow/generated/detect/rest/errors/UnauthorizedError.java new file mode 100644 index 00000000..63754690 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/errors/UnauthorizedError.java @@ -0,0 +1,33 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.errors; + +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.types.ErrorResponse; +import okhttp3.Response; + +public final class UnauthorizedError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final ErrorResponse body; + + public UnauthorizedError(ErrorResponse body) { + super("UnauthorizedError", 401, body); + this.body = body; + } + + public UnauthorizedError(ErrorResponse body, Response rawResponse) { + super("UnauthorizedError", 401, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public ErrorResponse body() { + return this.body; + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/AsyncFilesV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/AsyncFilesV2Client.java new file mode 100644 index 00000000..c032d144 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/AsyncFilesV2Client.java @@ -0,0 +1,85 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2; + +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.DeidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.GetRunV2Request; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.ReidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyFileResponseV2; +import com.skyflow.generated.detect.rest.types.DetectRunsResponseV2; +import com.skyflow.generated.detect.rest.types.ReidentifyFileResponseV2; +import java.util.concurrent.CompletableFuture; + +public class AsyncFilesV2Client { + protected final ClientOptions clientOptions; + + private final AsyncRawFilesV2Client rawClient; + + public AsyncFilesV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawFilesV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawFilesV2Client withRawResponse() { + return this.rawClient; + } + + /** + * De-identifies sensitive data from a file.

Note: + *

    + *
  • Layout may vary with token-based redaction for MS Office files (PPT, DOCX, and XLS) and PDFs when token-based PDF processing is selected.
  • + *
  • V2 API is in beta.
  • + *
+ */ + public CompletableFuture deidentifyFileV2(DeidentifyFileRequestV2 request) { + return this.rawClient.deidentifyFileV2(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a file.

Note: + *
    + *
  • Layout may vary with token-based redaction for MS Office files (PPT, DOCX, and XLS) and PDFs when token-based PDF processing is selected.
  • + *
  • V2 API is in beta.
  • + *
+ */ + public CompletableFuture deidentifyFileV2( + DeidentifyFileRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.deidentifyFileV2(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Re-identifies tokens in a file.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public CompletableFuture reidentifyFileV2(ReidentifyFileRequestV2 request) { + return this.rawClient.reidentifyFileV2(request).thenApply(response -> response.body()); + } + + /** + * Re-identifies tokens in a file.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public CompletableFuture reidentifyFileV2( + ReidentifyFileRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.reidentifyFileV2(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Returns the status of a detect run.

Note: V2 API is in beta. + */ + public CompletableFuture getRunV2(String runId, GetRunV2Request request) { + return this.rawClient.getRunV2(runId, request).thenApply(response -> response.body()); + } + + /** + * Returns the status of a detect run.

Note: V2 API is in beta. + */ + public CompletableFuture getRunV2( + String runId, GetRunV2Request request, RequestOptions requestOptions) { + return this.rawClient.getRunV2(runId, request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/AsyncRawFilesV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/AsyncRawFilesV2Client.java new file mode 100644 index 00000000..6764e32b --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/AsyncRawFilesV2Client.java @@ -0,0 +1,350 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.core.ApiClientException; +import com.skyflow.generated.detect.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.MediaTypes; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.core.QueryStringMapper; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.core.RetryInterceptor; +import com.skyflow.generated.detect.rest.errors.BadRequestError; +import com.skyflow.generated.detect.rest.errors.InternalServerError; +import com.skyflow.generated.detect.rest.errors.UnauthorizedError; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.DeidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.GetRunV2Request; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.ReidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyFileResponseV2; +import com.skyflow.generated.detect.rest.types.DetectRunsResponseV2; +import com.skyflow.generated.detect.rest.types.ErrorResponse; +import com.skyflow.generated.detect.rest.types.ReidentifyFileResponseV2; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawFilesV2Client { + protected final ClientOptions clientOptions; + + public AsyncRawFilesV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * De-identifies sensitive data from a file.

Note: + *
    + *
  • Layout may vary with token-based redaction for MS Office files (PPT, DOCX, and XLS) and PDFs when token-based PDF processing is selected.
  • + *
  • V2 API is in beta.
  • + *
+ */ + public CompletableFuture> deidentifyFileV2( + DeidentifyFileRequestV2 request) { + return deidentifyFileV2(request, null); + } + + /** + * De-identifies sensitive data from a file.

Note: + *
    + *
  • Layout may vary with token-based redaction for MS Office files (PPT, DOCX, and XLS) and PDFs when token-based PDF processing is selected.
  • + *
  • V2 API is in beta.
  • + *
+ */ + public CompletableFuture> deidentifyFileV2( + DeidentifyFileRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/deidentify/file"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeidentifyFileResponseV2.class), + response)); + return; + } + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Re-identifies tokens in a file.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public CompletableFuture> reidentifyFileV2( + ReidentifyFileRequestV2 request) { + return reidentifyFileV2(request, null); + } + + /** + * Re-identifies tokens in a file.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public CompletableFuture> reidentifyFileV2( + ReidentifyFileRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/reidentify/file"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ReidentifyFileResponseV2.class), + response)); + return; + } + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Returns the status of a detect run.

Note: V2 API is in beta. + */ + public CompletableFuture> getRunV2( + String runId, GetRunV2Request request) { + return getRunV2(runId, request, null); + } + + /** + * Returns the status of a detect run.

Note: V2 API is in beta. + */ + public CompletableFuture> getRunV2( + String runId, GetRunV2Request request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/runs") + .addPathSegment(runId); + QueryStringMapper.addQueryParameter(httpUrl, "vaultId", request.getVaultId(), false); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DetectRunsResponseV2.class), + response)); + return; + } + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/FilesV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/FilesV2Client.java new file mode 100644 index 00000000..9f9f8c1a --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/FilesV2Client.java @@ -0,0 +1,81 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2; + +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.DeidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.GetRunV2Request; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.ReidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyFileResponseV2; +import com.skyflow.generated.detect.rest.types.DetectRunsResponseV2; +import com.skyflow.generated.detect.rest.types.ReidentifyFileResponseV2; + +public class FilesV2Client { + protected final ClientOptions clientOptions; + + private final RawFilesV2Client rawClient; + + public FilesV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawFilesV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawFilesV2Client withRawResponse() { + return this.rawClient; + } + + /** + * De-identifies sensitive data from a file.

Note: + *
    + *
  • Layout may vary with token-based redaction for MS Office files (PPT, DOCX, and XLS) and PDFs when token-based PDF processing is selected.
  • + *
  • V2 API is in beta.
  • + *
+ */ + public DeidentifyFileResponseV2 deidentifyFileV2(DeidentifyFileRequestV2 request) { + return this.rawClient.deidentifyFileV2(request).body(); + } + + /** + * De-identifies sensitive data from a file.

Note: + *
    + *
  • Layout may vary with token-based redaction for MS Office files (PPT, DOCX, and XLS) and PDFs when token-based PDF processing is selected.
  • + *
  • V2 API is in beta.
  • + *
+ */ + public DeidentifyFileResponseV2 deidentifyFileV2(DeidentifyFileRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.deidentifyFileV2(request, requestOptions).body(); + } + + /** + * Re-identifies tokens in a file.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public ReidentifyFileResponseV2 reidentifyFileV2(ReidentifyFileRequestV2 request) { + return this.rawClient.reidentifyFileV2(request).body(); + } + + /** + * Re-identifies tokens in a file.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public ReidentifyFileResponseV2 reidentifyFileV2(ReidentifyFileRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.reidentifyFileV2(request, requestOptions).body(); + } + + /** + * Returns the status of a detect run.

Note: V2 API is in beta. + */ + public DetectRunsResponseV2 getRunV2(String runId, GetRunV2Request request) { + return this.rawClient.getRunV2(runId, request).body(); + } + + /** + * Returns the status of a detect run.

Note: V2 API is in beta. + */ + public DetectRunsResponseV2 getRunV2(String runId, GetRunV2Request request, RequestOptions requestOptions) { + return this.rawClient.getRunV2(runId, request, requestOptions).body(); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/RawFilesV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/RawFilesV2Client.java new file mode 100644 index 00000000..2ffe352d --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/RawFilesV2Client.java @@ -0,0 +1,282 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.core.ApiClientException; +import com.skyflow.generated.detect.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.MediaTypes; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.core.QueryStringMapper; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.core.RetryInterceptor; +import com.skyflow.generated.detect.rest.errors.BadRequestError; +import com.skyflow.generated.detect.rest.errors.InternalServerError; +import com.skyflow.generated.detect.rest.errors.UnauthorizedError; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.DeidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.GetRunV2Request; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.ReidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyFileResponseV2; +import com.skyflow.generated.detect.rest.types.DetectRunsResponseV2; +import com.skyflow.generated.detect.rest.types.ErrorResponse; +import com.skyflow.generated.detect.rest.types.ReidentifyFileResponseV2; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawFilesV2Client { + protected final ClientOptions clientOptions; + + public RawFilesV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * De-identifies sensitive data from a file.

Note: + *
    + *
  • Layout may vary with token-based redaction for MS Office files (PPT, DOCX, and XLS) and PDFs when token-based PDF processing is selected.
  • + *
  • V2 API is in beta.
  • + *
+ */ + public ApiClientHttpResponse deidentifyFileV2(DeidentifyFileRequestV2 request) { + return deidentifyFileV2(request, null); + } + + /** + * De-identifies sensitive data from a file.

Note: + *
    + *
  • Layout may vary with token-based redaction for MS Office files (PPT, DOCX, and XLS) and PDFs when token-based PDF processing is selected.
  • + *
  • V2 API is in beta.
  • + *
+ */ + public ApiClientHttpResponse deidentifyFileV2( + DeidentifyFileRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/deidentify/file"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeidentifyFileResponseV2.class), + response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Re-identifies tokens in a file.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse reidentifyFileV2(ReidentifyFileRequestV2 request) { + return reidentifyFileV2(request, null); + } + + /** + * Re-identifies tokens in a file.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse reidentifyFileV2( + ReidentifyFileRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/reidentify/file"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ReidentifyFileResponseV2.class), + response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Returns the status of a detect run.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse getRunV2(String runId, GetRunV2Request request) { + return getRunV2(runId, request, null); + } + + /** + * Returns the status of a detect run.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse getRunV2( + String runId, GetRunV2Request request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/runs") + .addPathSegment(runId); + QueryStringMapper.addQueryParameter(httpUrl, "vaultId", request.getVaultId(), false); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DetectRunsResponseV2.class), response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/DeidentifyFileRequestV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/DeidentifyFileRequestV2.java new file mode 100644 index 00000000..f95ee7ab --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/DeidentifyFileRequestV2.java @@ -0,0 +1,286 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.resources.filesv2.types.DeidentifyFileRequestV2DataFormat; +import com.skyflow.generated.detect.rest.resources.filesv2.types.DeidentifyFileRequestV2DataSource; +import com.skyflow.generated.detect.rest.types.DetectConfigV2; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyFileRequestV2.Builder.class) +public final class DeidentifyFileRequestV2 { + private final DeidentifyFileRequestV2DataSource dataSource; + + private final String value; + + private final Optional dataFormat; + + private final Optional configurationId; + + private final Optional configuration; + + private final Map additionalProperties; + + private DeidentifyFileRequestV2( + DeidentifyFileRequestV2DataSource dataSource, + String value, + Optional dataFormat, + Optional configurationId, + Optional configuration, + Map additionalProperties) { + this.dataSource = dataSource; + this.value = value; + this.dataFormat = dataFormat; + this.configurationId = configurationId; + this.configuration = configuration; + this.additionalProperties = additionalProperties; + } + + /** + * @return Data source of the input file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file. + */ + @JsonProperty("dataSource") + public DeidentifyFileRequestV2DataSource getDataSource() { + return dataSource; + } + + /** + * @return File data corresponding to the specified dataSource type. + */ + @JsonProperty("value") + public String getValue() { + return value; + } + + /** + * @return Format of the input file. The VAULT_TOKEN de-identification type is supported only for txt, json, csv, xml, jsonl, docx, xlsx, and pptx files. + */ + @JsonProperty("dataFormat") + public Optional getDataFormat() { + return dataFormat; + } + + /** + * @return ID of the Detect configuration to use for de-identification. + */ + @JsonProperty("configurationId") + public Optional getConfigurationId() { + return configurationId; + } + + @JsonProperty("configuration") + public Optional getConfiguration() { + return configuration; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyFileRequestV2 && equalTo((DeidentifyFileRequestV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyFileRequestV2 other) { + return dataSource.equals(other.dataSource) + && value.equals(other.value) + && dataFormat.equals(other.dataFormat) + && configurationId.equals(other.configurationId) + && configuration.equals(other.configuration); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.dataSource, this.value, this.dataFormat, this.configurationId, this.configuration); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static DataSourceStage builder() { + return new Builder(); + } + + public interface DataSourceStage { + /** + *

Data source of the input file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file.

+ */ + ValueStage dataSource(@NotNull DeidentifyFileRequestV2DataSource dataSource); + + Builder from(DeidentifyFileRequestV2 other); + } + + public interface ValueStage { + /** + *

File data corresponding to the specified dataSource type.

+ */ + _FinalStage value(@NotNull String value); + } + + public interface _FinalStage { + DeidentifyFileRequestV2 build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Format of the input file. The VAULT_TOKEN de-identification type is supported only for txt, json, csv, xml, jsonl, docx, xlsx, and pptx files.

+ */ + _FinalStage dataFormat(Optional dataFormat); + + _FinalStage dataFormat(DeidentifyFileRequestV2DataFormat dataFormat); + + /** + *

ID of the Detect configuration to use for de-identification.

+ */ + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + + _FinalStage configuration(Optional configuration); + + _FinalStage configuration(DetectConfigV2 configuration); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements DataSourceStage, ValueStage, _FinalStage { + private DeidentifyFileRequestV2DataSource dataSource; + + private String value; + + private Optional configuration = Optional.empty(); + + private Optional configurationId = Optional.empty(); + + private Optional dataFormat = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyFileRequestV2 other) { + dataSource(other.getDataSource()); + value(other.getValue()); + dataFormat(other.getDataFormat()); + configurationId(other.getConfigurationId()); + configuration(other.getConfiguration()); + return this; + } + + /** + *

Data source of the input file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file.

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

File data corresponding to the specified dataSource type.

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

ID of the Detect configuration to use for de-identification.

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

ID of the Detect configuration to use for de-identification.

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

Format of the input file. The VAULT_TOKEN de-identification type is supported only for txt, json, csv, xml, jsonl, docx, xlsx, and pptx files.

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

Format of the input file. The VAULT_TOKEN de-identification type is supported only for txt, json, csv, xml, jsonl, docx, xlsx, and pptx files.

+ */ + @java.lang.Override + @JsonSetter(value = "dataFormat", nulls = Nulls.SKIP) + public _FinalStage dataFormat(Optional dataFormat) { + this.dataFormat = dataFormat; + return this; + } + + @java.lang.Override + public DeidentifyFileRequestV2 build() { + return new DeidentifyFileRequestV2( + dataSource, value, dataFormat, configurationId, configuration, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/GetRunV2Request.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/GetRunV2Request.java new file mode 100644 index 00000000..f90f7153 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/GetRunV2Request.java @@ -0,0 +1,118 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetRunV2Request.Builder.class) +public final class GetRunV2Request { + private final String vaultId; + + private final Map additionalProperties; + + private GetRunV2Request(String vaultId, Map additionalProperties) { + this.vaultId = vaultId; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vaultId") + public String getVaultId() { + return vaultId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetRunV2Request && equalTo((GetRunV2Request) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetRunV2Request other) { + return vaultId.equals(other.vaultId); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(GetRunV2Request other); + } + + public interface _FinalStage { + GetRunV2Request build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(GetRunV2Request other) { + vaultId(other.getVaultId()); + return this; + } + + @java.lang.Override + @JsonSetter("vaultId") + public _FinalStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + @java.lang.Override + public GetRunV2Request build() { + return new GetRunV2Request(vaultId, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/ReidentifyFileRequestV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/ReidentifyFileRequestV2.java new file mode 100644 index 00000000..29751862 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/requests/ReidentifyFileRequestV2.java @@ -0,0 +1,291 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.resources.filesv2.types.ReidentifyFileRequestV2DataFormat; +import com.skyflow.generated.detect.rest.resources.filesv2.types.ReidentifyFileRequestV2DataSource; +import com.skyflow.generated.detect.rest.types.RedactionLevel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileRequestV2.Builder.class) +public final class ReidentifyFileRequestV2 { + private final ReidentifyFileRequestV2DataSource dataSource; + + private final String value; + + private final Optional dataFormat; + + private final String vaultId; + + private final Optional> redactionLevel; + + private final Map additionalProperties; + + private ReidentifyFileRequestV2( + ReidentifyFileRequestV2DataSource dataSource, + String value, + Optional dataFormat, + String vaultId, + Optional> redactionLevel, + Map additionalProperties) { + this.dataSource = dataSource; + this.value = value; + this.dataFormat = dataFormat; + this.vaultId = vaultId; + this.redactionLevel = redactionLevel; + this.additionalProperties = additionalProperties; + } + + /** + * @return Data source of the input file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file. + */ + @JsonProperty("dataSource") + public ReidentifyFileRequestV2DataSource getDataSource() { + return dataSource; + } + + /** + * @return File data corresponding to the specified dataSource type. + */ + @JsonProperty("value") + public String getValue() { + return value; + } + + /** + * @return Format of the input file. Limited to the formats that support the VAULT_TOKEN de-identification type. + */ + @JsonProperty("dataFormat") + public Optional getDataFormat() { + return dataFormat; + } + + /** + * @return ID of the vault used for de-identification. + */ + @JsonProperty("vaultId") + public String getVaultId() { + return vaultId; + } + + /** + * @return Replacement patterns or types applied to entity types or token groups during re-identification. Specifies a replacement pattern/type and the token group or entity type it applies to during re-identification. Set tokenGroupName for FlowVault and entityName for SkyVault. Similarly, set redactionType for FlowVault and redactionPattern for SkyVaultto specify the replacement. + */ + @JsonProperty("redactionLevel") + public Optional> getRedactionLevel() { + return redactionLevel; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileRequestV2 && equalTo((ReidentifyFileRequestV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileRequestV2 other) { + return dataSource.equals(other.dataSource) + && value.equals(other.value) + && dataFormat.equals(other.dataFormat) + && vaultId.equals(other.vaultId) + && redactionLevel.equals(other.redactionLevel); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.dataSource, this.value, this.dataFormat, this.vaultId, this.redactionLevel); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static DataSourceStage builder() { + return new Builder(); + } + + public interface DataSourceStage { + /** + *

Data source of the input file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file.

+ */ + ValueStage dataSource(@NotNull ReidentifyFileRequestV2DataSource dataSource); + + Builder from(ReidentifyFileRequestV2 other); + } + + public interface ValueStage { + /** + *

File data corresponding to the specified dataSource type.

+ */ + VaultIdStage value(@NotNull String value); + } + + public interface VaultIdStage { + /** + *

ID of the vault used for de-identification.

+ */ + _FinalStage vaultId(@NotNull String vaultId); + } + + public interface _FinalStage { + ReidentifyFileRequestV2 build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Format of the input file. Limited to the formats that support the VAULT_TOKEN de-identification type.

+ */ + _FinalStage dataFormat(Optional dataFormat); + + _FinalStage dataFormat(ReidentifyFileRequestV2DataFormat dataFormat); + + /** + *

Replacement patterns or types applied to entity types or token groups during re-identification. Specifies a replacement pattern/type and the token group or entity type it applies to during re-identification. Set tokenGroupName for FlowVault and entityName for SkyVault. Similarly, set redactionType for FlowVault and redactionPattern for SkyVaultto specify the replacement.

+ */ + _FinalStage redactionLevel(Optional> redactionLevel); + + _FinalStage redactionLevel(List redactionLevel); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements DataSourceStage, ValueStage, VaultIdStage, _FinalStage { + private ReidentifyFileRequestV2DataSource dataSource; + + private String value; + + private String vaultId; + + private Optional> redactionLevel = Optional.empty(); + + private Optional dataFormat = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ReidentifyFileRequestV2 other) { + dataSource(other.getDataSource()); + value(other.getValue()); + dataFormat(other.getDataFormat()); + vaultId(other.getVaultId()); + redactionLevel(other.getRedactionLevel()); + return this; + } + + /** + *

Data source of the input file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file.

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

File data corresponding to the specified dataSource type.

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

ID of the vault used for de-identification.

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

Replacement patterns or types applied to entity types or token groups during re-identification. Specifies a replacement pattern/type and the token group or entity type it applies to during re-identification. Set tokenGroupName for FlowVault and entityName for SkyVault. Similarly, set redactionType for FlowVault and redactionPattern for SkyVaultto specify the replacement.

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

Replacement patterns or types applied to entity types or token groups during re-identification. Specifies a replacement pattern/type and the token group or entity type it applies to during re-identification. Set tokenGroupName for FlowVault and entityName for SkyVault. Similarly, set redactionType for FlowVault and redactionPattern for SkyVaultto specify the replacement.

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

Format of the input file. Limited to the formats that support the VAULT_TOKEN de-identification type.

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

Format of the input file. Limited to the formats that support the VAULT_TOKEN de-identification type.

+ */ + @java.lang.Override + @JsonSetter(value = "dataFormat", nulls = Nulls.SKIP) + public _FinalStage dataFormat(Optional dataFormat) { + this.dataFormat = dataFormat; + return this; + } + + @java.lang.Override + public ReidentifyFileRequestV2 build() { + return new ReidentifyFileRequestV2( + dataSource, value, dataFormat, vaultId, redactionLevel, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/DeidentifyFileRequestV2DataFormat.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/DeidentifyFileRequestV2DataFormat.java new file mode 100644 index 00000000..6a4aaf01 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/DeidentifyFileRequestV2DataFormat.java @@ -0,0 +1,301 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DeidentifyFileRequestV2DataFormat { + public static final DeidentifyFileRequestV2DataFormat BMP = new DeidentifyFileRequestV2DataFormat(Value.BMP, "bmp"); + + public static final DeidentifyFileRequestV2DataFormat PPTX = + new DeidentifyFileRequestV2DataFormat(Value.PPTX, "pptx"); + + public static final DeidentifyFileRequestV2DataFormat WAV = new DeidentifyFileRequestV2DataFormat(Value.WAV, "wav"); + + public static final DeidentifyFileRequestV2DataFormat DOC = new DeidentifyFileRequestV2DataFormat(Value.DOC, "doc"); + + public static final DeidentifyFileRequestV2DataFormat XML = new DeidentifyFileRequestV2DataFormat(Value.XML, "xml"); + + public static final DeidentifyFileRequestV2DataFormat ZIP = new DeidentifyFileRequestV2DataFormat(Value.ZIP, "zip"); + + public static final DeidentifyFileRequestV2DataFormat MP3 = new DeidentifyFileRequestV2DataFormat(Value.MP3, "mp3"); + + public static final DeidentifyFileRequestV2DataFormat PPT = new DeidentifyFileRequestV2DataFormat(Value.PPT, "ppt"); + + public static final DeidentifyFileRequestV2DataFormat JPEG = + new DeidentifyFileRequestV2DataFormat(Value.JPEG, "jpeg"); + + public static final DeidentifyFileRequestV2DataFormat TIFF = + new DeidentifyFileRequestV2DataFormat(Value.TIFF, "tiff"); + + public static final DeidentifyFileRequestV2DataFormat PDF = new DeidentifyFileRequestV2DataFormat(Value.PDF, "pdf"); + + public static final DeidentifyFileRequestV2DataFormat DOCX = + new DeidentifyFileRequestV2DataFormat(Value.DOCX, "docx"); + + public static final DeidentifyFileRequestV2DataFormat PNG = new DeidentifyFileRequestV2DataFormat(Value.PNG, "png"); + + public static final DeidentifyFileRequestV2DataFormat JSONL = + new DeidentifyFileRequestV2DataFormat(Value.JSONL, "jsonl"); + + public static final DeidentifyFileRequestV2DataFormat CSV = new DeidentifyFileRequestV2DataFormat(Value.CSV, "csv"); + + public static final DeidentifyFileRequestV2DataFormat JPG = new DeidentifyFileRequestV2DataFormat(Value.JPG, "jpg"); + + public static final DeidentifyFileRequestV2DataFormat DCM = new DeidentifyFileRequestV2DataFormat(Value.DCM, "dcm"); + + public static final DeidentifyFileRequestV2DataFormat JSON = + new DeidentifyFileRequestV2DataFormat(Value.JSON, "json"); + + public static final DeidentifyFileRequestV2DataFormat GIF = new DeidentifyFileRequestV2DataFormat(Value.GIF, "gif"); + + public static final DeidentifyFileRequestV2DataFormat TXT = new DeidentifyFileRequestV2DataFormat(Value.TXT, "txt"); + + public static final DeidentifyFileRequestV2DataFormat XLS = new DeidentifyFileRequestV2DataFormat(Value.XLS, "xls"); + + public static final DeidentifyFileRequestV2DataFormat XLSX = + new DeidentifyFileRequestV2DataFormat(Value.XLSX, "xlsx"); + + public static final DeidentifyFileRequestV2DataFormat TIF = new DeidentifyFileRequestV2DataFormat(Value.TIF, "tif"); + + private final Value value; + + private final String string; + + DeidentifyFileRequestV2DataFormat(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DeidentifyFileRequestV2DataFormat + && this.string.equals(((DeidentifyFileRequestV2DataFormat) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BMP: + return visitor.visitBmp(); + case PPTX: + return visitor.visitPptx(); + case WAV: + return visitor.visitWav(); + case DOC: + return visitor.visitDoc(); + case XML: + return visitor.visitXml(); + case ZIP: + return visitor.visitZip(); + case MP3: + return visitor.visitMp3(); + case PPT: + return visitor.visitPpt(); + case JPEG: + return visitor.visitJpeg(); + case TIFF: + return visitor.visitTiff(); + case PDF: + return visitor.visitPdf(); + case DOCX: + return visitor.visitDocx(); + case PNG: + return visitor.visitPng(); + case JSONL: + return visitor.visitJsonl(); + case CSV: + return visitor.visitCsv(); + case JPG: + return visitor.visitJpg(); + case DCM: + return visitor.visitDcm(); + case JSON: + return visitor.visitJson(); + case GIF: + return visitor.visitGif(); + case TXT: + return visitor.visitTxt(); + case XLS: + return visitor.visitXls(); + case XLSX: + return visitor.visitXlsx(); + case TIF: + return visitor.visitTif(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DeidentifyFileRequestV2DataFormat valueOf(String value) { + switch (value) { + case "bmp": + return BMP; + case "pptx": + return PPTX; + case "wav": + return WAV; + case "doc": + return DOC; + case "xml": + return XML; + case "zip": + return ZIP; + case "mp3": + return MP3; + case "ppt": + return PPT; + case "jpeg": + return JPEG; + case "tiff": + return TIFF; + case "pdf": + return PDF; + case "docx": + return DOCX; + case "png": + return PNG; + case "jsonl": + return JSONL; + case "csv": + return CSV; + case "jpg": + return JPG; + case "dcm": + return DCM; + case "json": + return JSON; + case "gif": + return GIF; + case "txt": + return TXT; + case "xls": + return XLS; + case "xlsx": + return XLSX; + case "tif": + return TIF; + default: + return new DeidentifyFileRequestV2DataFormat(Value.UNKNOWN, value); + } + } + + public enum Value { + MP3, + + WAV, + + PDF, + + TXT, + + CSV, + + JSON, + + JPG, + + JPEG, + + TIF, + + TIFF, + + PNG, + + BMP, + + XLS, + + XLSX, + + DOC, + + DOCX, + + PPT, + + PPTX, + + XML, + + DCM, + + JSONL, + + ZIP, + + GIF, + + UNKNOWN + } + + public interface Visitor { + T visitMp3(); + + T visitWav(); + + T visitPdf(); + + T visitTxt(); + + T visitCsv(); + + T visitJson(); + + T visitJpg(); + + T visitJpeg(); + + T visitTif(); + + T visitTiff(); + + T visitPng(); + + T visitBmp(); + + T visitXls(); + + T visitXlsx(); + + T visitDoc(); + + T visitDocx(); + + T visitPpt(); + + T visitPptx(); + + T visitXml(); + + T visitDcm(); + + T visitJsonl(); + + T visitZip(); + + T visitGif(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/DeidentifyFileRequestV2DataSource.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/DeidentifyFileRequestV2DataSource.java new file mode 100644 index 00000000..83c9aed3 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/DeidentifyFileRequestV2DataSource.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DeidentifyFileRequestV2DataSource { + public static final DeidentifyFileRequestV2DataSource BASE64 = + new DeidentifyFileRequestV2DataSource(Value.BASE64, "BASE64"); + + public static final DeidentifyFileRequestV2DataSource SKYFLOW_ID = + new DeidentifyFileRequestV2DataSource(Value.SKYFLOW_ID, "SKYFLOW_ID"); + + public static final DeidentifyFileRequestV2DataSource PRESIGNED_URL = + new DeidentifyFileRequestV2DataSource(Value.PRESIGNED_URL, "PRESIGNED_URL"); + + private final Value value; + + private final String string; + + DeidentifyFileRequestV2DataSource(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DeidentifyFileRequestV2DataSource + && this.string.equals(((DeidentifyFileRequestV2DataSource) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BASE64: + return visitor.visitBase64(); + case SKYFLOW_ID: + return visitor.visitSkyflowId(); + case PRESIGNED_URL: + return visitor.visitPresignedUrl(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DeidentifyFileRequestV2DataSource valueOf(String value) { + switch (value) { + case "BASE64": + return BASE64; + case "SKYFLOW_ID": + return SKYFLOW_ID; + case "PRESIGNED_URL": + return PRESIGNED_URL; + default: + return new DeidentifyFileRequestV2DataSource(Value.UNKNOWN, value); + } + } + + public enum Value { + BASE64, + + SKYFLOW_ID, + + PRESIGNED_URL, + + UNKNOWN + } + + public interface Visitor { + T visitBase64(); + + T visitSkyflowId(); + + T visitPresignedUrl(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/ReidentifyFileRequestV2DataFormat.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/ReidentifyFileRequestV2DataFormat.java new file mode 100644 index 00000000..df3c688f --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/ReidentifyFileRequestV2DataFormat.java @@ -0,0 +1,149 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class ReidentifyFileRequestV2DataFormat { + public static final ReidentifyFileRequestV2DataFormat PPTX = + new ReidentifyFileRequestV2DataFormat(Value.PPTX, "pptx"); + + public static final ReidentifyFileRequestV2DataFormat JSONL = + new ReidentifyFileRequestV2DataFormat(Value.JSONL, "jsonl"); + + public static final ReidentifyFileRequestV2DataFormat CSV = new ReidentifyFileRequestV2DataFormat(Value.CSV, "csv"); + + public static final ReidentifyFileRequestV2DataFormat XML = new ReidentifyFileRequestV2DataFormat(Value.XML, "xml"); + + public static final ReidentifyFileRequestV2DataFormat JSON = + new ReidentifyFileRequestV2DataFormat(Value.JSON, "json"); + + public static final ReidentifyFileRequestV2DataFormat TXT = new ReidentifyFileRequestV2DataFormat(Value.TXT, "txt"); + + public static final ReidentifyFileRequestV2DataFormat DOCX = + new ReidentifyFileRequestV2DataFormat(Value.DOCX, "docx"); + + public static final ReidentifyFileRequestV2DataFormat XLSX = + new ReidentifyFileRequestV2DataFormat(Value.XLSX, "xlsx"); + + private final Value value; + + private final String string; + + ReidentifyFileRequestV2DataFormat(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ReidentifyFileRequestV2DataFormat + && this.string.equals(((ReidentifyFileRequestV2DataFormat) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case PPTX: + return visitor.visitPptx(); + case JSONL: + return visitor.visitJsonl(); + case CSV: + return visitor.visitCsv(); + case XML: + return visitor.visitXml(); + case JSON: + return visitor.visitJson(); + case TXT: + return visitor.visitTxt(); + case DOCX: + return visitor.visitDocx(); + case XLSX: + return visitor.visitXlsx(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ReidentifyFileRequestV2DataFormat valueOf(String value) { + switch (value) { + case "pptx": + return PPTX; + case "jsonl": + return JSONL; + case "csv": + return CSV; + case "xml": + return XML; + case "json": + return JSON; + case "txt": + return TXT; + case "docx": + return DOCX; + case "xlsx": + return XLSX; + default: + return new ReidentifyFileRequestV2DataFormat(Value.UNKNOWN, value); + } + } + + public enum Value { + TXT, + + CSV, + + JSON, + + XLSX, + + DOCX, + + PPTX, + + XML, + + JSONL, + + UNKNOWN + } + + public interface Visitor { + T visitTxt(); + + T visitCsv(); + + T visitJson(); + + T visitXlsx(); + + T visitDocx(); + + T visitPptx(); + + T visitXml(); + + T visitJsonl(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/ReidentifyFileRequestV2DataSource.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/ReidentifyFileRequestV2DataSource.java new file mode 100644 index 00000000..538cbc49 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/filesv2/types/ReidentifyFileRequestV2DataSource.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.filesv2.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class ReidentifyFileRequestV2DataSource { + public static final ReidentifyFileRequestV2DataSource BASE64 = + new ReidentifyFileRequestV2DataSource(Value.BASE64, "BASE64"); + + public static final ReidentifyFileRequestV2DataSource SKYFLOW_ID = + new ReidentifyFileRequestV2DataSource(Value.SKYFLOW_ID, "SKYFLOW_ID"); + + public static final ReidentifyFileRequestV2DataSource PRESIGNED_URL = + new ReidentifyFileRequestV2DataSource(Value.PRESIGNED_URL, "PRESIGNED_URL"); + + private final Value value; + + private final String string; + + ReidentifyFileRequestV2DataSource(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ReidentifyFileRequestV2DataSource + && this.string.equals(((ReidentifyFileRequestV2DataSource) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BASE64: + return visitor.visitBase64(); + case SKYFLOW_ID: + return visitor.visitSkyflowId(); + case PRESIGNED_URL: + return visitor.visitPresignedUrl(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ReidentifyFileRequestV2DataSource valueOf(String value) { + switch (value) { + case "BASE64": + return BASE64; + case "SKYFLOW_ID": + return SKYFLOW_ID; + case "PRESIGNED_URL": + return PRESIGNED_URL; + default: + return new ReidentifyFileRequestV2DataSource(Value.UNKNOWN, value); + } + } + + public enum Value { + BASE64, + + SKYFLOW_ID, + + PRESIGNED_URL, + + UNKNOWN + } + + public interface Visitor { + T visitBase64(); + + T visitSkyflowId(); + + T visitPresignedUrl(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/AsyncGuardrailsV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/AsyncGuardrailsV2Client.java new file mode 100644 index 00000000..fe74a2d3 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/AsyncGuardrailsV2Client.java @@ -0,0 +1,43 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.guardrailsv2; + +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.resources.guardrailsv2.requests.DetectGuardrailsRequestV2; +import com.skyflow.generated.detect.rest.types.DetectGuardrailsResponseV2; +import java.util.concurrent.CompletableFuture; + +public class AsyncGuardrailsV2Client { + protected final ClientOptions clientOptions; + + private final AsyncRawGuardrailsV2Client rawClient; + + public AsyncGuardrailsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawGuardrailsV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawGuardrailsV2Client withRawResponse() { + return this.rawClient; + } + + /** + * Preserve safety and compliance with usage policies.

Note: V2 API is in beta. + */ + public CompletableFuture checkGuardrailsV2(DetectGuardrailsRequestV2 request) { + return this.rawClient.checkGuardrailsV2(request).thenApply(response -> response.body()); + } + + /** + * Preserve safety and compliance with usage policies.

Note: V2 API is in beta. + */ + public CompletableFuture checkGuardrailsV2( + DetectGuardrailsRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.checkGuardrailsV2(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncRawGuardrailsClient.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/AsyncRawGuardrailsV2Client.java similarity index 54% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncRawGuardrailsClient.java rename to common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/AsyncRawGuardrailsV2Client.java index 80853472..c6b84c0e 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncRawGuardrailsClient.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/AsyncRawGuardrailsV2Client.java @@ -1,46 +1,64 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.resources.guardrails; +package com.skyflow.generated.detect.rest.resources.guardrailsv2; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.BadRequestError; -import com.skyflow.generated.rest.errors.InternalServerError; -import com.skyflow.generated.rest.errors.UnauthorizedError; -import com.skyflow.generated.rest.resources.guardrails.requests.DetectGuardrailsRequest; -import com.skyflow.generated.rest.types.DetectGuardrailsResponse; -import com.skyflow.generated.rest.types.ErrorResponse; -import okhttp3.*; -import org.jetbrains.annotations.NotNull; - +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.core.ApiClientException; +import com.skyflow.generated.detect.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.MediaTypes; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.core.RetryInterceptor; +import com.skyflow.generated.detect.rest.errors.BadRequestError; +import com.skyflow.generated.detect.rest.errors.InternalServerError; +import com.skyflow.generated.detect.rest.errors.UnauthorizedError; +import com.skyflow.generated.detect.rest.resources.guardrailsv2.requests.DetectGuardrailsRequestV2; +import com.skyflow.generated.detect.rest.types.DetectGuardrailsResponseV2; +import com.skyflow.generated.detect.rest.types.ErrorResponse; import java.io.IOException; import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; -public class AsyncRawGuardrailsClient { +public class AsyncRawGuardrailsV2Client { protected final ClientOptions clientOptions; - public AsyncRawGuardrailsClient(ClientOptions clientOptions) { + public AsyncRawGuardrailsV2Client(ClientOptions clientOptions) { this.clientOptions = clientOptions; } /** - * Preserve safety and compliance with usage policies. + * Preserve safety and compliance with usage policies.

Note: V2 API is in beta. */ - public CompletableFuture> checkGuardrails( - DetectGuardrailsRequest request) { - return checkGuardrails(request, null); + public CompletableFuture> checkGuardrailsV2( + DetectGuardrailsRequestV2 request) { + return checkGuardrailsV2(request, null); } /** - * Preserve safety and compliance with usage policies. + * Preserve safety and compliance with usage policies.

Note: V2 API is in beta. */ - public CompletableFuture> checkGuardrails( - DetectGuardrailsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> checkGuardrailsV2( + DetectGuardrailsRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() - .addPathSegments("v1/detect/guardrails") - .build(); + .addPathSegments("v2/detect/guardrails"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -49,7 +67,7 @@ public CompletableFuture> checkG throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -59,29 +77,38 @@ public CompletableFuture> checkG if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DetectGuardrailsResponse.class), + responseBodyString, DetectGuardrailsResponseV2.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 401: future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 500: @@ -93,12 +120,13 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/GuardrailsV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/GuardrailsV2Client.java new file mode 100644 index 00000000..2d3a9bf7 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/GuardrailsV2Client.java @@ -0,0 +1,42 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.guardrailsv2; + +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.resources.guardrailsv2.requests.DetectGuardrailsRequestV2; +import com.skyflow.generated.detect.rest.types.DetectGuardrailsResponseV2; + +public class GuardrailsV2Client { + protected final ClientOptions clientOptions; + + private final RawGuardrailsV2Client rawClient; + + public GuardrailsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawGuardrailsV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawGuardrailsV2Client withRawResponse() { + return this.rawClient; + } + + /** + * Preserve safety and compliance with usage policies.

Note: V2 API is in beta. + */ + public DetectGuardrailsResponseV2 checkGuardrailsV2(DetectGuardrailsRequestV2 request) { + return this.rawClient.checkGuardrailsV2(request).body(); + } + + /** + * Preserve safety and compliance with usage policies.

Note: V2 API is in beta. + */ + public DetectGuardrailsResponseV2 checkGuardrailsV2( + DetectGuardrailsRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.checkGuardrailsV2(request, requestOptions).body(); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/RawGuardrailsV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/RawGuardrailsV2Client.java new file mode 100644 index 00000000..c124c516 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/RawGuardrailsV2Client.java @@ -0,0 +1,116 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.guardrailsv2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.core.ApiClientException; +import com.skyflow.generated.detect.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.MediaTypes; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.core.RetryInterceptor; +import com.skyflow.generated.detect.rest.errors.BadRequestError; +import com.skyflow.generated.detect.rest.errors.InternalServerError; +import com.skyflow.generated.detect.rest.errors.UnauthorizedError; +import com.skyflow.generated.detect.rest.resources.guardrailsv2.requests.DetectGuardrailsRequestV2; +import com.skyflow.generated.detect.rest.types.DetectGuardrailsResponseV2; +import com.skyflow.generated.detect.rest.types.ErrorResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawGuardrailsV2Client { + protected final ClientOptions clientOptions; + + public RawGuardrailsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Preserve safety and compliance with usage policies.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse checkGuardrailsV2(DetectGuardrailsRequestV2 request) { + return checkGuardrailsV2(request, null); + } + + /** + * Preserve safety and compliance with usage policies.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse checkGuardrailsV2( + DetectGuardrailsRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/guardrails"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DetectGuardrailsResponseV2.class), + response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/requests/DetectGuardrailsRequest.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/requests/DetectGuardrailsRequestV2.java similarity index 67% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/requests/DetectGuardrailsRequest.java rename to common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/requests/DetectGuardrailsRequestV2.java index 75250f8c..f6d8dbad 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/requests/DetectGuardrailsRequest.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/guardrailsv2/requests/DetectGuardrailsRequestV2.java @@ -1,18 +1,27 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.resources.guardrails.requests; - -import com.fasterxml.jackson.annotation.*; +package com.skyflow.generated.detect.rest.resources.guardrailsv2.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.jetbrains.annotations.NotNull; -import java.util.*; - @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DetectGuardrailsRequest.Builder.class) -public final class DetectGuardrailsRequest { +@JsonDeserialize(builder = DetectGuardrailsRequestV2.Builder.class) +public final class DetectGuardrailsRequestV2 { private final String text; private final Optional checkToxicity; @@ -23,7 +32,7 @@ public final class DetectGuardrailsRequest { private final Map additionalProperties; - private DetectGuardrailsRequest( + private DetectGuardrailsRequestV2( String text, Optional checkToxicity, Optional> denyTopics, @@ -47,7 +56,7 @@ public String getText() { /** * @return If true, checks for toxicity in the text. */ - @JsonProperty("check_toxicity") + @JsonProperty("checkToxicity") public Optional getCheckToxicity() { return checkToxicity; } @@ -55,7 +64,7 @@ public Optional getCheckToxicity() { /** * @return List of topics to deny. */ - @JsonProperty("deny_topics") + @JsonProperty("denyTopics") public Optional> getDenyTopics() { return denyTopics; } @@ -63,15 +72,15 @@ public Optional> getDenyTopics() { /** * @return ID of the vault. */ - @JsonProperty("vault_id") + @JsonProperty("vaultId") public String getVaultId() { return vaultId; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof DetectGuardrailsRequest && equalTo((DetectGuardrailsRequest) other); + return other instanceof DetectGuardrailsRequestV2 && equalTo((DetectGuardrailsRequestV2) other); } @JsonAnyGetter @@ -79,19 +88,19 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(DetectGuardrailsRequest other) { + private boolean equalTo(DetectGuardrailsRequestV2 other) { return text.equals(other.text) && checkToxicity.equals(other.checkToxicity) && denyTopics.equals(other.denyTopics) && vaultId.equals(other.vaultId); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.text, this.checkToxicity, this.denyTopics, this.vaultId); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -102,22 +111,26 @@ public static TextStage builder() { public interface TextStage { /** - * Text to check against guardrails. + *

Text to check against guardrails.

*/ VaultIdStage text(@NotNull String text); - Builder from(DetectGuardrailsRequest other); + Builder from(DetectGuardrailsRequestV2 other); } public interface VaultIdStage { /** - * ID of the vault. + *

ID of the vault.

*/ _FinalStage vaultId(@NotNull String vaultId); } public interface _FinalStage { - DetectGuardrailsRequest build(); + DetectGuardrailsRequestV2 build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); /** *

If true, checks for toxicity in the text.

@@ -149,8 +162,8 @@ public static final class Builder implements TextStage, VaultIdStage, _FinalStag private Builder() {} - @Override - public Builder from(DetectGuardrailsRequest other) { + @java.lang.Override + public Builder from(DetectGuardrailsRequestV2 other) { text(other.getText()); checkToxicity(other.getCheckToxicity()); denyTopics(other.getDenyTopics()); @@ -159,10 +172,10 @@ public Builder from(DetectGuardrailsRequest other) { } /** - * Text to check against guardrails.

Text to check against guardrails.

+ *

Text to check against guardrails.

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

ID of the vault.

+ *

ID of the vault.

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

List of topics to deny.

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

List of topics to deny.

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

If true, checks for toxicity in the text.

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

If true, checks for toxicity in the text.

*/ - @Override - @JsonSetter(value = "check_toxicity", nulls = Nulls.SKIP) + @java.lang.Override + @JsonSetter(value = "checkToxicity", nulls = Nulls.SKIP) public _FinalStage checkToxicity(Optional checkToxicity) { this.checkToxicity = checkToxicity; return this; } - @Override - public DetectGuardrailsRequest build() { - return new DetectGuardrailsRequest(text, checkToxicity, denyTopics, vaultId, additionalProperties); + @java.lang.Override + public DetectGuardrailsRequestV2 build() { + return new DetectGuardrailsRequestV2(text, checkToxicity, denyTopics, vaultId, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncRawStringsClient.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/AsyncRawStringsV2Client.java similarity index 55% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncRawStringsClient.java rename to common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/AsyncRawStringsV2Client.java index 36b364b5..cac69231 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncRawStringsClient.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/AsyncRawStringsV2Client.java @@ -1,48 +1,66 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.resources.strings; +package com.skyflow.generated.detect.rest.resources.stringsv2; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.BadRequestError; -import com.skyflow.generated.rest.errors.InternalServerError; -import com.skyflow.generated.rest.errors.UnauthorizedError; -import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; -import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; -import com.skyflow.generated.rest.types.DeidentifyStringResponse; -import com.skyflow.generated.rest.types.ErrorResponse; -import com.skyflow.generated.rest.types.IdentifyResponse; -import okhttp3.*; -import org.jetbrains.annotations.NotNull; - +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.core.ApiClientException; +import com.skyflow.generated.detect.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.MediaTypes; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.core.RetryInterceptor; +import com.skyflow.generated.detect.rest.errors.BadRequestError; +import com.skyflow.generated.detect.rest.errors.InternalServerError; +import com.skyflow.generated.detect.rest.errors.UnauthorizedError; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.DeidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.ReidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2; +import com.skyflow.generated.detect.rest.types.ErrorResponse; +import com.skyflow.generated.detect.rest.types.ReidentifyStringResponseV2; import java.io.IOException; import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; -public class AsyncRawStringsClient { +public class AsyncRawStringsV2Client { protected final ClientOptions clientOptions; - public AsyncRawStringsClient(ClientOptions clientOptions) { + public AsyncRawStringsV2Client(ClientOptions clientOptions) { this.clientOptions = clientOptions; } /** - * De-identifies sensitive data from a string. + * De-identifies sensitive data from a string.

Note: V2 API is in beta. */ - public CompletableFuture> deidentifyString( - DeidentifyStringRequest request) { - return deidentifyString(request, null); + public CompletableFuture> deidentifyStringV2( + DeidentifyStringRequestV2 request) { + return deidentifyStringV2(request, null); } /** - * De-identifies sensitive data from a string. + * De-identifies sensitive data from a string.

Note: V2 API is in beta. */ - public CompletableFuture> deidentifyString( - DeidentifyStringRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> deidentifyStringV2( + DeidentifyStringRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() - .addPathSegments("v1/detect/deidentify/string") - .build(); + .addPathSegments("v2/detect/deidentify/string"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -51,7 +69,7 @@ public CompletableFuture> deiden throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -61,29 +79,38 @@ public CompletableFuture> deiden if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyStringResponse.class), + responseBodyString, DeidentifyStringResponseV2.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 401: future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 500: @@ -95,12 +122,13 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } @@ -115,29 +143,26 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { } /** - * Re-identifies tokens in a string. - */ - public CompletableFuture> reidentifyString() { - return reidentifyString(ReidentifyStringRequest.builder().build()); - } - - /** - * Re-identifies tokens in a string. + * Re-identifies tokens in a string.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. */ - public CompletableFuture> reidentifyString( - ReidentifyStringRequest request) { - return reidentifyString(request, null); + public CompletableFuture> reidentifyStringV2( + ReidentifyStringRequestV2 request) { + return reidentifyStringV2(request, null); } /** - * Re-identifies tokens in a string. + * Re-identifies tokens in a string.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. */ - public CompletableFuture> reidentifyString( - ReidentifyStringRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> reidentifyStringV2( + ReidentifyStringRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() - .addPathSegments("v1/detect/reidentify/string") - .build(); + .addPathSegments("v2/detect/reidentify/string"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -146,7 +171,7 @@ public CompletableFuture> reidentifyStri throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -156,28 +181,38 @@ public CompletableFuture> reidentifyStri if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), IdentifyResponse.class), + ObjectMappers.JSON_MAPPER.readValue( + responseBodyString, ReidentifyStringResponseV2.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 401: future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 500: @@ -189,12 +224,13 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/AsyncStringsV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/AsyncStringsV2Client.java new file mode 100644 index 00000000..47c34f06 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/AsyncStringsV2Client.java @@ -0,0 +1,60 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.stringsv2; + +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.DeidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.ReidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2; +import com.skyflow.generated.detect.rest.types.ReidentifyStringResponseV2; +import java.util.concurrent.CompletableFuture; + +public class AsyncStringsV2Client { + protected final ClientOptions clientOptions; + + private final AsyncRawStringsV2Client rawClient; + + public AsyncStringsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawStringsV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawStringsV2Client withRawResponse() { + return this.rawClient; + } + + /** + * De-identifies sensitive data from a string.

Note: V2 API is in beta. + */ + public CompletableFuture deidentifyStringV2(DeidentifyStringRequestV2 request) { + return this.rawClient.deidentifyStringV2(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a string.

Note: V2 API is in beta. + */ + public CompletableFuture deidentifyStringV2( + DeidentifyStringRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.deidentifyStringV2(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Re-identifies tokens in a string.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public CompletableFuture reidentifyStringV2(ReidentifyStringRequestV2 request) { + return this.rawClient.reidentifyStringV2(request).thenApply(response -> response.body()); + } + + /** + * Re-identifies tokens in a string.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public CompletableFuture reidentifyStringV2( + ReidentifyStringRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.reidentifyStringV2(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/RawStringsV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/RawStringsV2Client.java new file mode 100644 index 00000000..61f71478 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/RawStringsV2Client.java @@ -0,0 +1,198 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.stringsv2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.core.ApiClientException; +import com.skyflow.generated.detect.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.MediaTypes; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.core.RetryInterceptor; +import com.skyflow.generated.detect.rest.errors.BadRequestError; +import com.skyflow.generated.detect.rest.errors.InternalServerError; +import com.skyflow.generated.detect.rest.errors.UnauthorizedError; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.DeidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.ReidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2; +import com.skyflow.generated.detect.rest.types.ErrorResponse; +import com.skyflow.generated.detect.rest.types.ReidentifyStringResponseV2; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawStringsV2Client { + protected final ClientOptions clientOptions; + + public RawStringsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * De-identifies sensitive data from a string.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse deidentifyStringV2(DeidentifyStringRequestV2 request) { + return deidentifyStringV2(request, null); + } + + /** + * De-identifies sensitive data from a string.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse deidentifyStringV2( + DeidentifyStringRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/deidentify/string"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeidentifyStringResponseV2.class), + response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Re-identifies tokens in a string.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse reidentifyStringV2(ReidentifyStringRequestV2 request) { + return reidentifyStringV2(request, null); + } + + /** + * Re-identifies tokens in a string.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public ApiClientHttpResponse reidentifyStringV2( + ReidentifyStringRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/detect/reidentify/string"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ReidentifyStringResponseV2.class), + response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/StringsV2Client.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/StringsV2Client.java new file mode 100644 index 00000000..2a50d897 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/StringsV2Client.java @@ -0,0 +1,59 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.stringsv2; + +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.DeidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.ReidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2; +import com.skyflow.generated.detect.rest.types.ReidentifyStringResponseV2; + +public class StringsV2Client { + protected final ClientOptions clientOptions; + + private final RawStringsV2Client rawClient; + + public StringsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawStringsV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawStringsV2Client withRawResponse() { + return this.rawClient; + } + + /** + * De-identifies sensitive data from a string.

Note: V2 API is in beta. + */ + public DeidentifyStringResponseV2 deidentifyStringV2(DeidentifyStringRequestV2 request) { + return this.rawClient.deidentifyStringV2(request).body(); + } + + /** + * De-identifies sensitive data from a string.

Note: V2 API is in beta. + */ + public DeidentifyStringResponseV2 deidentifyStringV2( + DeidentifyStringRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.deidentifyStringV2(request, requestOptions).body(); + } + + /** + * Re-identifies tokens in a string.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public ReidentifyStringResponseV2 reidentifyStringV2(ReidentifyStringRequestV2 request) { + return this.rawClient.reidentifyStringV2(request).body(); + } + + /** + * Re-identifies tokens in a string.

Requires the Detect Invoker, Detect Manager, or Vault Owner role. Re-identifying vault_token values also requires a policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

Note: V2 API is in beta. + */ + public ReidentifyStringResponseV2 reidentifyStringV2( + ReidentifyStringRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.reidentifyStringV2(request, requestOptions).body(); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/requests/DeidentifyStringRequestV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/requests/DeidentifyStringRequestV2.java new file mode 100644 index 00000000..c3964a6d --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/requests/DeidentifyStringRequestV2.java @@ -0,0 +1,206 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.stringsv2.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.types.DetectConfigV2; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyStringRequestV2.Builder.class) +public final class DeidentifyStringRequestV2 { + private final String text; + + private final Optional configurationId; + + private final Optional configuration; + + private final Map additionalProperties; + + private DeidentifyStringRequestV2( + String text, + Optional configurationId, + Optional configuration, + Map additionalProperties) { + this.text = text; + this.configurationId = configurationId; + this.configuration = configuration; + this.additionalProperties = additionalProperties; + } + + /** + * @return Text to deidentify. + */ + @JsonProperty("text") + public String getText() { + return text; + } + + /** + * @return ID of the Detect configuration to use for de-identification. + */ + @JsonProperty("configurationId") + public Optional getConfigurationId() { + return configurationId; + } + + @JsonProperty("configuration") + public Optional getConfiguration() { + return configuration; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyStringRequestV2 && equalTo((DeidentifyStringRequestV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyStringRequestV2 other) { + return text.equals(other.text) + && configurationId.equals(other.configurationId) + && configuration.equals(other.configuration); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.text, this.configurationId, this.configuration); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TextStage builder() { + return new Builder(); + } + + public interface TextStage { + /** + *

Text to deidentify.

+ */ + _FinalStage text(@NotNull String text); + + Builder from(DeidentifyStringRequestV2 other); + } + + public interface _FinalStage { + DeidentifyStringRequestV2 build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

ID of the Detect configuration to use for de-identification.

+ */ + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + + _FinalStage configuration(Optional configuration); + + _FinalStage configuration(DetectConfigV2 configuration); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TextStage, _FinalStage { + private String text; + + private Optional configuration = Optional.empty(); + + private Optional configurationId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyStringRequestV2 other) { + text(other.getText()); + configurationId(other.getConfigurationId()); + configuration(other.getConfiguration()); + return this; + } + + /** + *

Text to deidentify.

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

ID of the Detect configuration to use for de-identification.

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

ID of the Detect configuration to use for de-identification.

+ */ + @java.lang.Override + @JsonSetter(value = "configurationId", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + + @java.lang.Override + public DeidentifyStringRequestV2 build() { + return new DeidentifyStringRequestV2(text, configurationId, configuration, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/requests/ReidentifyStringRequestV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/requests/ReidentifyStringRequestV2.java new file mode 100644 index 00000000..b242a87b --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/resources/stringsv2/requests/ReidentifyStringRequestV2.java @@ -0,0 +1,209 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.resources.stringsv2.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.types.RedactionLevel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyStringRequestV2.Builder.class) +public final class ReidentifyStringRequestV2 { + private final String vaultId; + + private final String text; + + private final Optional> redactionLevel; + + private final Map additionalProperties; + + private ReidentifyStringRequestV2( + String vaultId, + String text, + Optional> redactionLevel, + Map additionalProperties) { + this.vaultId = vaultId; + this.text = text; + this.redactionLevel = redactionLevel; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault used for re-identification. Requires the Detect Invoker, Detect Manager, or Vault Owner role for this vault. Re-identifying vault_token values also requires a role or policy that separately grants the Detokenization action, unless the caller has the Vault Owner role. + */ + @JsonProperty("vaultId") + public String getVaultId() { + return vaultId; + } + + /** + * @return Text to reidentify. + */ + @JsonProperty("text") + public String getText() { + return text; + } + + /** + * @return Replacement patterns or types applied to entity types or token groups during re-identification. Specifies a replacement pattern/type and the token group or entity type it applies to during re-identification. Set exactly one of tokenGroupName or entityName. Use tokenGroupName for FlowVault and entityName for SkyVault. Similarly, set exactly one of redactionType or redactionPattern to specify the replacement. + */ + @JsonProperty("redactionLevel") + public Optional> getRedactionLevel() { + return redactionLevel; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyStringRequestV2 && equalTo((ReidentifyStringRequestV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyStringRequestV2 other) { + return vaultId.equals(other.vaultId) && text.equals(other.text) && redactionLevel.equals(other.redactionLevel); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.text, this.redactionLevel); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

ID of the vault used for re-identification. Requires the Detect Invoker, Detect Manager, or Vault Owner role for this vault. Re-identifying vault_token values also requires a role or policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

+ */ + TextStage vaultId(@NotNull String vaultId); + + Builder from(ReidentifyStringRequestV2 other); + } + + public interface TextStage { + /** + *

Text to reidentify.

+ */ + _FinalStage text(@NotNull String text); + } + + public interface _FinalStage { + ReidentifyStringRequestV2 build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Replacement patterns or types applied to entity types or token groups during re-identification. Specifies a replacement pattern/type and the token group or entity type it applies to during re-identification. Set exactly one of tokenGroupName or entityName. Use tokenGroupName for FlowVault and entityName for SkyVault. Similarly, set exactly one of redactionType or redactionPattern to specify the replacement.

+ */ + _FinalStage redactionLevel(Optional> redactionLevel); + + _FinalStage redactionLevel(List redactionLevel); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, TextStage, _FinalStage { + private String vaultId; + + private String text; + + private Optional> redactionLevel = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ReidentifyStringRequestV2 other) { + vaultId(other.getVaultId()); + text(other.getText()); + redactionLevel(other.getRedactionLevel()); + return this; + } + + /** + *

ID of the vault used for re-identification. Requires the Detect Invoker, Detect Manager, or Vault Owner role for this vault. Re-identifying vault_token values also requires a role or policy that separately grants the Detokenization action, unless the caller has the Vault Owner role.

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

Text to reidentify.

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

Replacement patterns or types applied to entity types or token groups during re-identification. Specifies a replacement pattern/type and the token group or entity type it applies to during re-identification. Set exactly one of tokenGroupName or entityName. Use tokenGroupName for FlowVault and entityName for SkyVault. Similarly, set exactly one of redactionType or redactionPattern to specify the replacement.

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

Replacement patterns or types applied to entity types or token groups during re-identification. Specifies a replacement pattern/type and the token group or entity type it applies to during re-identification. Set exactly one of tokenGroupName or entityName. Use tokenGroupName for FlowVault and entityName for SkyVault. Similarly, set exactly one of redactionType or redactionPattern to specify the replacement.

+ */ + @java.lang.Override + @JsonSetter(value = "redactionLevel", nulls = Nulls.SKIP) + public _FinalStage redactionLevel(Optional> redactionLevel) { + this.redactionLevel = redactionLevel; + return this; + } + + @java.lang.Override + public ReidentifyStringRequestV2 build() { + return new ReidentifyStringRequestV2(vaultId, text, redactionLevel, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2.java new file mode 100644 index 00000000..eb4be5de --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2.java @@ -0,0 +1,167 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AudioV2.Builder.class) +public final class AudioV2 { + private final Optional outputProcessedAudio; + + private final Optional outputTranscription; + + private final Optional bleep; + + private final Map additionalProperties; + + private AudioV2( + Optional outputProcessedAudio, + Optional outputTranscription, + Optional bleep, + Map additionalProperties) { + this.outputProcessedAudio = outputProcessedAudio; + this.outputTranscription = outputTranscription; + this.bleep = bleep; + this.additionalProperties = additionalProperties; + } + + /** + * @return If true, includes processed audio file in the response. Can't be used together with outputTranscription. + */ + @JsonProperty("outputProcessedAudio") + public Optional getOutputProcessedAudio() { + return outputProcessedAudio; + } + + /** + * @return Type of transcription to include in the response. TRANSCRIPTION: standard transcript of the audio. MEDICAL_TRANSCRIPTION: transcript focused on medical content and terminology. DIARIZED_TRANSCRIPTION: speaker-separated transcript that labels each speaker's dialogue. MEDICAL_DIARIZED_TRANSCRIPTION: speaker-separated transcript focused on medical content and terminology. NONE: no transcription is included. Can't be used together with outputProcessedAudio. + */ + @JsonProperty("outputTranscription") + public Optional getOutputTranscription() { + return outputTranscription; + } + + @JsonProperty("bleep") + public Optional getBleep() { + return bleep; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AudioV2 && equalTo((AudioV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AudioV2 other) { + return outputProcessedAudio.equals(other.outputProcessedAudio) + && outputTranscription.equals(other.outputTranscription) + && bleep.equals(other.bleep); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.outputProcessedAudio, this.outputTranscription, this.bleep); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional outputProcessedAudio = Optional.empty(); + + private Optional outputTranscription = Optional.empty(); + + private Optional bleep = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(AudioV2 other) { + outputProcessedAudio(other.getOutputProcessedAudio()); + outputTranscription(other.getOutputTranscription()); + bleep(other.getBleep()); + return this; + } + + /** + *

If true, includes processed audio file in the response. Can't be used together with outputTranscription.

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

Type of transcription to include in the response. TRANSCRIPTION: standard transcript of the audio. MEDICAL_TRANSCRIPTION: transcript focused on medical content and terminology. DIARIZED_TRANSCRIPTION: speaker-separated transcript that labels each speaker's dialogue. MEDICAL_DIARIZED_TRANSCRIPTION: speaker-separated transcript focused on medical content and terminology. NONE: no transcription is included. Can't be used together with outputProcessedAudio.

+ */ + @JsonSetter(value = "outputTranscription", nulls = Nulls.SKIP) + public Builder outputTranscription(Optional outputTranscription) { + this.outputTranscription = outputTranscription; + return this; + } + + public Builder outputTranscription(AudioV2OutputTranscription outputTranscription) { + this.outputTranscription = Optional.ofNullable(outputTranscription); + return this; + } + + @JsonSetter(value = "bleep", nulls = Nulls.SKIP) + public Builder bleep(Optional bleep) { + this.bleep = bleep; + return this; + } + + public Builder bleep(AudioV2Bleep bleep) { + this.bleep = Optional.ofNullable(bleep); + return this; + } + + public AudioV2 build() { + return new AudioV2(outputProcessedAudio, outputTranscription, bleep, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2Bleep.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2Bleep.java new file mode 100644 index 00000000..eb234230 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2Bleep.java @@ -0,0 +1,203 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AudioV2Bleep.Builder.class) +public final class AudioV2Bleep { + private final Optional startPadding; + + private final Optional stopPadding; + + private final Optional frequency; + + private final Optional gain; + + private final Map additionalProperties; + + private AudioV2Bleep( + Optional startPadding, + Optional stopPadding, + Optional frequency, + Optional gain, + Map additionalProperties) { + this.startPadding = startPadding; + this.stopPadding = stopPadding; + this.frequency = frequency; + this.gain = gain; + this.additionalProperties = additionalProperties; + } + + /** + * @return Padding added to the beginning of a bleep, in seconds. Range: 0–20. Defaults to 0.5. + */ + @JsonProperty("startPadding") + public Optional getStartPadding() { + return startPadding; + } + + /** + * @return Padding added to the end of a bleep, in seconds. Range: 0–20. Defaults to 0.2. + */ + @JsonProperty("stopPadding") + public Optional getStopPadding() { + return stopPadding; + } + + /** + * @return Frequency of the sine wave used for the bleep sound, in Hz. + */ + @JsonProperty("frequency") + public Optional getFrequency() { + return frequency; + } + + /** + * @return Relative loudness of the bleep. Positive values increase loudness and negative values decrease it. + */ + @JsonProperty("gain") + public Optional getGain() { + return gain; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AudioV2Bleep && equalTo((AudioV2Bleep) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AudioV2Bleep other) { + return startPadding.equals(other.startPadding) + && stopPadding.equals(other.stopPadding) + && frequency.equals(other.frequency) + && gain.equals(other.gain); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.startPadding, this.stopPadding, this.frequency, this.gain); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional startPadding = Optional.empty(); + + private Optional stopPadding = Optional.empty(); + + private Optional frequency = Optional.empty(); + + private Optional gain = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(AudioV2Bleep other) { + startPadding(other.getStartPadding()); + stopPadding(other.getStopPadding()); + frequency(other.getFrequency()); + gain(other.getGain()); + return this; + } + + /** + *

Padding added to the beginning of a bleep, in seconds. Range: 0–20. Defaults to 0.5.

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

Padding added to the end of a bleep, in seconds. Range: 0–20. Defaults to 0.2.

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

Frequency of the sine wave used for the bleep sound, in Hz.

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

Relative loudness of the bleep. Positive values increase loudness and negative values decrease it.

+ */ + @JsonSetter(value = "gain", nulls = Nulls.SKIP) + public Builder gain(Optional gain) { + this.gain = gain; + return this; + } + + public Builder gain(Integer gain) { + this.gain = Optional.ofNullable(gain); + return this; + } + + public AudioV2Bleep build() { + return new AudioV2Bleep(startPadding, stopPadding, frequency, gain, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2OutputTranscription.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2OutputTranscription.java new file mode 100644 index 00000000..9d48255f --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/AudioV2OutputTranscription.java @@ -0,0 +1,118 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class AudioV2OutputTranscription { + public static final AudioV2OutputTranscription NONE = new AudioV2OutputTranscription(Value.NONE, "NONE"); + + public static final AudioV2OutputTranscription TRANSCRIPTION = + new AudioV2OutputTranscription(Value.TRANSCRIPTION, "TRANSCRIPTION"); + + public static final AudioV2OutputTranscription MEDICAL_TRANSCRIPTION = + new AudioV2OutputTranscription(Value.MEDICAL_TRANSCRIPTION, "MEDICAL_TRANSCRIPTION"); + + public static final AudioV2OutputTranscription DIARIZED_TRANSCRIPTION = + new AudioV2OutputTranscription(Value.DIARIZED_TRANSCRIPTION, "DIARIZED_TRANSCRIPTION"); + + public static final AudioV2OutputTranscription MEDICAL_DIARIZED_TRANSCRIPTION = + new AudioV2OutputTranscription(Value.MEDICAL_DIARIZED_TRANSCRIPTION, "MEDICAL_DIARIZED_TRANSCRIPTION"); + + private final Value value; + + private final String string; + + AudioV2OutputTranscription(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof AudioV2OutputTranscription + && this.string.equals(((AudioV2OutputTranscription) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case NONE: + return visitor.visitNone(); + case TRANSCRIPTION: + return visitor.visitTranscription(); + case MEDICAL_TRANSCRIPTION: + return visitor.visitMedicalTranscription(); + case DIARIZED_TRANSCRIPTION: + return visitor.visitDiarizedTranscription(); + case MEDICAL_DIARIZED_TRANSCRIPTION: + return visitor.visitMedicalDiarizedTranscription(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static AudioV2OutputTranscription valueOf(String value) { + switch (value) { + case "NONE": + return NONE; + case "TRANSCRIPTION": + return TRANSCRIPTION; + case "MEDICAL_TRANSCRIPTION": + return MEDICAL_TRANSCRIPTION; + case "DIARIZED_TRANSCRIPTION": + return DIARIZED_TRANSCRIPTION; + case "MEDICAL_DIARIZED_TRANSCRIPTION": + return MEDICAL_DIARIZED_TRANSCRIPTION; + default: + return new AudioV2OutputTranscription(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + TRANSCRIPTION, + + MEDICAL_TRANSCRIPTION, + + DIARIZED_TRANSCRIPTION, + + MEDICAL_DIARIZED_TRANSCRIPTION, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitTranscription(); + + T visitMedicalTranscription(); + + T visitDiarizedTranscription(); + + T visitMedicalDiarizedTranscription(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileResponse.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyFileResponseV2.java similarity index 50% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileResponse.java rename to common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyFileResponseV2.java index d5a2ebd5..fa5b77eb 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileResponse.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyFileResponseV2.java @@ -1,41 +1,46 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - +import com.skyflow.generated.detect.rest.core.ObjectMappers; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileResponse.Builder.class) -public final class DeidentifyFileResponse { +@JsonDeserialize(builder = DeidentifyFileResponseV2.Builder.class) +public final class DeidentifyFileResponseV2 { private final Optional runId; private final Map additionalProperties; - private DeidentifyFileResponse(Optional runId, Map additionalProperties) { + private DeidentifyFileResponseV2(Optional runId, Map additionalProperties) { this.runId = runId; this.additionalProperties = additionalProperties; } /** - * @return Status URL for the Detect run. + * @return Run ID of the deidentification request. */ - @JsonProperty("run_id") + @JsonProperty("runId") public Optional getRunId() { return runId; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof DeidentifyFileResponse && equalTo((DeidentifyFileResponse) other); + return other instanceof DeidentifyFileResponseV2 && equalTo((DeidentifyFileResponseV2) other); } @JsonAnyGetter @@ -43,16 +48,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(DeidentifyFileResponse other) { + private boolean equalTo(DeidentifyFileResponseV2 other) { return runId.equals(other.runId); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.runId); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -70,15 +75,15 @@ public static final class Builder { private Builder() {} - public Builder from(DeidentifyFileResponse other) { + public Builder from(DeidentifyFileResponseV2 other) { runId(other.getRunId()); return this; } /** - *

Status URL for the Detect run.

+ *

Run ID of the deidentification request.

*/ - @JsonSetter(value = "run_id", nulls = Nulls.SKIP) + @JsonSetter(value = "runId", nulls = Nulls.SKIP) public Builder runId(Optional runId) { this.runId = runId; return this; @@ -89,8 +94,18 @@ public Builder runId(String runId) { return this; } - public DeidentifyFileResponse build() { - return new DeidentifyFileResponse(runId, additionalProperties); + public DeidentifyFileResponseV2 build() { + return new DeidentifyFileResponseV2(runId, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2.java new file mode 100644 index 00000000..eb0eca2d --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2.java @@ -0,0 +1,168 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyStringResponseV2.Builder.class) +public final class DeidentifyStringResponseV2 { + private final Optional processedText; + + private final Optional> entities; + + private final Optional metrics; + + private final Map additionalProperties; + + private DeidentifyStringResponseV2( + Optional processedText, + Optional> entities, + Optional metrics, + Map additionalProperties) { + this.processedText = processedText; + this.entities = entities; + this.metrics = metrics; + this.additionalProperties = additionalProperties; + } + + /** + * @return Deidentified text with sensitive entities replaced. + */ + @JsonProperty("processedText") + public Optional getProcessedText() { + return processedText; + } + + /** + * @return Detected entities. + */ + @JsonProperty("entities") + public Optional> getEntities() { + return entities; + } + + @JsonProperty("metrics") + public Optional getMetrics() { + return metrics; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyStringResponseV2 && equalTo((DeidentifyStringResponseV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyStringResponseV2 other) { + return processedText.equals(other.processedText) + && entities.equals(other.entities) + && metrics.equals(other.metrics); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.processedText, this.entities, this.metrics); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional processedText = Optional.empty(); + + private Optional> entities = Optional.empty(); + + private Optional metrics = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DeidentifyStringResponseV2 other) { + processedText(other.getProcessedText()); + entities(other.getEntities()); + metrics(other.getMetrics()); + return this; + } + + /** + *

Deidentified text with sensitive entities replaced.

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

Detected entities.

+ */ + @JsonSetter(value = "entities", nulls = Nulls.SKIP) + public Builder entities(Optional> entities) { + this.entities = entities; + return this; + } + + public Builder entities(List entities) { + this.entities = Optional.ofNullable(entities); + return this; + } + + @JsonSetter(value = "metrics", nulls = Nulls.SKIP) + public Builder metrics(Optional metrics) { + this.metrics = metrics; + return this; + } + + public Builder metrics(Metrics metrics) { + this.metrics = Optional.ofNullable(metrics); + return this; + } + + public DeidentifyStringResponseV2 build() { + return new DeidentifyStringResponseV2(processedText, entities, metrics, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/StringResponseEntities.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2DetectedEntity.java similarity index 67% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/StringResponseEntities.java rename to common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2DetectedEntity.java index 78df8838..e3bf15bd 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/StringResponseEntities.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2DetectedEntity.java @@ -1,25 +1,30 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - +import com.skyflow.generated.detect.rest.core.ObjectMappers; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = StringResponseEntities.Builder.class) -public final class StringResponseEntities { +@JsonDeserialize(builder = DeidentifyStringResponseV2DetectedEntity.Builder.class) +public final class DeidentifyStringResponseV2DetectedEntity { private final Optional token; private final Optional value; - private final Optional location; + private final Optional location; private final Optional entityType; @@ -27,10 +32,10 @@ public final class StringResponseEntities { private final Map additionalProperties; - private StringResponseEntities( + private DeidentifyStringResponseV2DetectedEntity( Optional token, Optional value, - Optional location, + Optional location, Optional entityType, Optional> entityScores, Map additionalProperties) { @@ -59,14 +64,14 @@ public Optional getValue() { } @JsonProperty("location") - public Optional getLocation() { + public Optional getLocation() { return location; } /** * @return Highest-rated label. */ - @JsonProperty("entity_type") + @JsonProperty("entityType") public Optional getEntityType() { return entityType; } @@ -74,15 +79,16 @@ public Optional getEntityType() { /** * @return Labels and their scores. */ - @JsonProperty("entity_scores") + @JsonProperty("entityScores") public Optional> getEntityScores() { return entityScores; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof StringResponseEntities && equalTo((StringResponseEntities) other); + return other instanceof DeidentifyStringResponseV2DetectedEntity + && equalTo((DeidentifyStringResponseV2DetectedEntity) other); } @JsonAnyGetter @@ -90,7 +96,7 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(StringResponseEntities other) { + private boolean equalTo(DeidentifyStringResponseV2DetectedEntity other) { return token.equals(other.token) && value.equals(other.value) && location.equals(other.location) @@ -98,12 +104,12 @@ private boolean equalTo(StringResponseEntities other) { && entityScores.equals(other.entityScores); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.token, this.value, this.location, this.entityType, this.entityScores); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -118,7 +124,7 @@ public static final class Builder { private Optional value = Optional.empty(); - private Optional location = Optional.empty(); + private Optional location = Optional.empty(); private Optional entityType = Optional.empty(); @@ -129,7 +135,7 @@ public static final class Builder { private Builder() {} - public Builder from(StringResponseEntities other) { + public Builder from(DeidentifyStringResponseV2DetectedEntity other) { token(other.getToken()); value(other.getValue()); location(other.getLocation()); @@ -167,12 +173,12 @@ public Builder value(String value) { } @JsonSetter(value = "location", nulls = Nulls.SKIP) - public Builder location(Optional location) { + public Builder location(Optional location) { this.location = location; return this; } - public Builder location(Locations location) { + public Builder location(DeidentifyStringResponseV2EntityLocation location) { this.location = Optional.ofNullable(location); return this; } @@ -180,7 +186,7 @@ public Builder location(Locations location) { /** *

Highest-rated label.

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

Labels and their scores.

*/ - @JsonSetter(value = "entity_scores", nulls = Nulls.SKIP) + @JsonSetter(value = "entityScores", nulls = Nulls.SKIP) public Builder entityScores(Optional> entityScores) { this.entityScores = entityScores; return this; @@ -205,8 +211,19 @@ public Builder entityScores(Map entityScores) { return this; } - public StringResponseEntities build() { - return new StringResponseEntities(token, value, location, entityType, entityScores, additionalProperties); + public DeidentifyStringResponseV2DetectedEntity build() { + return new DeidentifyStringResponseV2DetectedEntity( + token, value, location, entityType, entityScores, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/Locations.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2EntityLocation.java similarity index 71% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/Locations.java rename to common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2EntityLocation.java index 4b95c485..6ac6a633 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/Locations.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DeidentifyStringResponseV2EntityLocation.java @@ -1,20 +1,25 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - +import com.skyflow.generated.detect.rest.core.ObjectMappers; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = Locations.Builder.class) -public final class Locations { +@JsonDeserialize(builder = DeidentifyStringResponseV2EntityLocation.Builder.class) +public final class DeidentifyStringResponseV2EntityLocation { private final Optional startIndex; private final Optional endIndex; @@ -25,7 +30,7 @@ public final class Locations { private final Map additionalProperties; - private Locations( + private DeidentifyStringResponseV2EntityLocation( Optional startIndex, Optional endIndex, Optional startIndexProcessed, @@ -41,7 +46,7 @@ private Locations( /** * @return Index of the first character of the string in the original text. */ - @JsonProperty("start_index") + @JsonProperty("startIndex") public Optional getStartIndex() { return startIndex; } @@ -49,7 +54,7 @@ public Optional getStartIndex() { /** * @return Index of the last character of the string in the original text. */ - @JsonProperty("end_index") + @JsonProperty("endIndex") public Optional getEndIndex() { return endIndex; } @@ -57,7 +62,7 @@ public Optional getEndIndex() { /** * @return Index of the first character of the string in the processed text. */ - @JsonProperty("start_index_processed") + @JsonProperty("startIndexProcessed") public Optional getStartIndexProcessed() { return startIndexProcessed; } @@ -65,15 +70,16 @@ public Optional getStartIndexProcessed() { /** * @return Index of the last character of the string in the processed text. */ - @JsonProperty("end_index_processed") + @JsonProperty("endIndexProcessed") public Optional getEndIndexProcessed() { return endIndexProcessed; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof Locations && equalTo((Locations) other); + return other instanceof DeidentifyStringResponseV2EntityLocation + && equalTo((DeidentifyStringResponseV2EntityLocation) other); } @JsonAnyGetter @@ -81,19 +87,19 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(Locations other) { + private boolean equalTo(DeidentifyStringResponseV2EntityLocation other) { return startIndex.equals(other.startIndex) && endIndex.equals(other.endIndex) && startIndexProcessed.equals(other.startIndexProcessed) && endIndexProcessed.equals(other.endIndexProcessed); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.startIndex, this.endIndex, this.startIndexProcessed, this.endIndexProcessed); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -117,7 +123,7 @@ public static final class Builder { private Builder() {} - public Builder from(Locations other) { + public Builder from(DeidentifyStringResponseV2EntityLocation other) { startIndex(other.getStartIndex()); endIndex(other.getEndIndex()); startIndexProcessed(other.getStartIndexProcessed()); @@ -128,7 +134,7 @@ public Builder from(Locations other) { /** *

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

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

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

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

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

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

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

*/ - @JsonSetter(value = "end_index_processed", nulls = Nulls.SKIP) + @JsonSetter(value = "endIndexProcessed", nulls = Nulls.SKIP) public Builder endIndexProcessed(Optional endIndexProcessed) { this.endIndexProcessed = endIndexProcessed; return this; @@ -181,8 +187,19 @@ public Builder endIndexProcessed(Integer endIndexProcessed) { return this; } - public Locations build() { - return new Locations(startIndex, endIndex, startIndexProcessed, endIndexProcessed, additionalProperties); + public DeidentifyStringResponseV2EntityLocation build() { + return new DeidentifyStringResponseV2EntityLocation( + startIndex, endIndex, startIndexProcessed, endIndexProcessed, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/Detect.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/Detect.java new file mode 100644 index 00000000..4935b1d0 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/Detect.java @@ -0,0 +1,266 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = Detect.Builder.class) +public final class Detect { + private final Optional> entities; + + private final Optional> objectEntities; + + private final Optional> restrict; + + private final Optional> skip; + + private final Optional> customTypes; + + private final Optional returnEntities; + + private final Map additionalProperties; + + private Detect( + Optional> entities, + Optional> objectEntities, + Optional> restrict, + Optional> skip, + Optional> customTypes, + Optional returnEntities, + Map additionalProperties) { + this.entities = entities; + this.objectEntities = objectEntities; + this.restrict = restrict; + this.skip = skip; + this.customTypes = customTypes; + this.returnEntities = returnEntities; + this.additionalProperties = additionalProperties; + } + + /** + * @return Entities and their deidentification settings. + */ + @JsonProperty("entities") + public Optional> getEntities() { + return entities; + } + + /** + * @return Object entities and their deidentification settings. + */ + @JsonProperty("objectEntities") + public Optional> getObjectEntities() { + return objectEntities; + } + + /** + * @return Settings for restricting detected entities. A detected entity is replaced with '[RESTRICTED]' only when a restrict pattern matches the entity's full value. If a pattern matches only a substring of the detected entity, the pattern is ignored and the entity is processed according to the configured tokenization and transformation settings. Patterns don't match across entity boundaries. If an entity matches both a skip and a restrict pattern, skip takes precedence and the entity is displayed in plaintext. Note: Vault tokens are currently not supported. + */ + @JsonProperty("restrict") + public Optional> getRestrict() { + return restrict; + } + + /** + * @return Settings for bypassing deidentification on detected entities. A detected entity is displayed in plaintext when a skip pattern matches either the entity's full value or any substring of it. Patterns don't match across entity boundaries. If an entity matches both a skip and a restrict pattern, skip takes precedence and the entity is displayed in plaintext. + */ + @JsonProperty("skip") + public Optional> getSkip() { + return skip; + } + + /** + * @return Custom entity type definitions. + */ + @JsonProperty("customTypes") + public Optional> getCustomTypes() { + return customTypes; + } + + /** + * @return Controls which detected entities are returned in the response. EXCLUDE_SENSITIVE_DATA: returns each detected entity's metadata (token, entity type, location, and confidence scores) but omits the original sensitive value. ALL: returns each detected entity's metadata and the original sensitive value. NONE: doesn't return detected entities. + */ + @JsonProperty("returnEntities") + public Optional getReturnEntities() { + return returnEntities; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof Detect && equalTo((Detect) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(Detect other) { + return entities.equals(other.entities) + && objectEntities.equals(other.objectEntities) + && restrict.equals(other.restrict) + && skip.equals(other.skip) + && customTypes.equals(other.customTypes) + && returnEntities.equals(other.returnEntities); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.entities, this.objectEntities, this.restrict, this.skip, this.customTypes, this.returnEntities); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> entities = Optional.empty(); + + private Optional> objectEntities = Optional.empty(); + + private Optional> restrict = Optional.empty(); + + private Optional> skip = Optional.empty(); + + private Optional> customTypes = Optional.empty(); + + private Optional returnEntities = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(Detect other) { + entities(other.getEntities()); + objectEntities(other.getObjectEntities()); + restrict(other.getRestrict()); + skip(other.getSkip()); + customTypes(other.getCustomTypes()); + returnEntities(other.getReturnEntities()); + return this; + } + + /** + *

Entities and their deidentification settings.

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

Object entities and their deidentification settings.

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

Settings for restricting detected entities. A detected entity is replaced with '[RESTRICTED]' only when a restrict pattern matches the entity's full value. If a pattern matches only a substring of the detected entity, the pattern is ignored and the entity is processed according to the configured tokenization and transformation settings. Patterns don't match across entity boundaries. If an entity matches both a skip and a restrict pattern, skip takes precedence and the entity is displayed in plaintext. Note: Vault tokens are currently not supported.

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

Settings for bypassing deidentification on detected entities. A detected entity is displayed in plaintext when a skip pattern matches either the entity's full value or any substring of it. Patterns don't match across entity boundaries. If an entity matches both a skip and a restrict pattern, skip takes precedence and the entity is displayed in plaintext.

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

Custom entity type definitions.

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

Controls which detected entities are returned in the response. EXCLUDE_SENSITIVE_DATA: returns each detected entity's metadata (token, entity type, location, and confidence scores) but omits the original sensitive value. ALL: returns each detected entity's metadata and the original sensitive value. NONE: doesn't return detected entities.

+ */ + @JsonSetter(value = "returnEntities", nulls = Nulls.SKIP) + public Builder returnEntities(Optional returnEntities) { + this.returnEntities = returnEntities; + return this; + } + + public Builder returnEntities(DetectReturnEntities returnEntities) { + this.returnEntities = Optional.ofNullable(returnEntities); + return this; + } + + public Detect build() { + return new Detect( + entities, objectEntities, restrict, skip, customTypes, returnEntities, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectConfigV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectConfigV2.java new file mode 100644 index 00000000..77f00c81 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectConfigV2.java @@ -0,0 +1,470 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectConfigV2.Builder.class) +public final class DetectConfigV2 { + private final Optional id; + + private final Optional name; + + private final Optional namespace; + + private final Optional description; + + private final String vaultId; + + private final Optional vaultType; + + private final Optional detect; + + private final Optional> fileMapping; + + private final Optional media; + + private final Map additionalProperties; + + private DetectConfigV2( + Optional id, + Optional name, + Optional namespace, + Optional description, + String vaultId, + Optional vaultType, + Optional detect, + Optional> fileMapping, + Optional media, + Map additionalProperties) { + this.id = id; + this.name = name; + this.namespace = namespace; + this.description = description; + this.vaultId = vaultId; + this.vaultType = vaultType; + this.detect = detect; + this.fileMapping = fileMapping; + this.media = media; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the configuration. + */ + @JsonProperty("ID") + public Optional getId() { + return id; + } + + /** + * @return Name of the configuration. + */ + @JsonProperty("name") + public Optional getName() { + return name; + } + + /** + * @return Namespace of the configuration. + */ + @JsonProperty("namespace") + public Optional getNamespace() { + return namespace; + } + + /** + * @return Description of the configuration. + */ + @JsonProperty("description") + public Optional getDescription() { + return description; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultId") + public String getVaultId() { + return vaultId; + } + + /** + * @return Type of the vault. + */ + @JsonProperty("vaultType") + public Optional getVaultType() { + return vaultType; + } + + @JsonProperty("detect") + public Optional getDetect() { + return detect; + } + + /** + * @return Mappings for source and deidentified file locations. + */ + @JsonProperty("fileMapping") + public Optional> getFileMapping() { + return fileMapping; + } + + @JsonProperty("media") + public Optional getMedia() { + return media; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectConfigV2 && equalTo((DetectConfigV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectConfigV2 other) { + return id.equals(other.id) + && name.equals(other.name) + && namespace.equals(other.namespace) + && description.equals(other.description) + && vaultId.equals(other.vaultId) + && vaultType.equals(other.vaultType) + && detect.equals(other.detect) + && fileMapping.equals(other.fileMapping) + && media.equals(other.media); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.id, + this.name, + this.namespace, + this.description, + this.vaultId, + this.vaultType, + this.detect, + this.fileMapping, + this.media); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

ID of the vault.

+ */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(DetectConfigV2 other); + } + + public interface _FinalStage { + DetectConfigV2 build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

ID of the configuration.

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

Name of the configuration.

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

Namespace of the configuration.

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

Description of the configuration.

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

Type of the vault.

+ */ + _FinalStage vaultType(Optional vaultType); + + _FinalStage vaultType(DetectConfigV2VaultType vaultType); + + _FinalStage detect(Optional detect); + + _FinalStage detect(Detect detect); + + /** + *

Mappings for source and deidentified file locations.

+ */ + _FinalStage fileMapping(Optional> fileMapping); + + _FinalStage fileMapping(List fileMapping); + + _FinalStage media(Optional media); + + _FinalStage media(Media media); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private Optional media = Optional.empty(); + + private Optional> fileMapping = Optional.empty(); + + private Optional detect = Optional.empty(); + + private Optional vaultType = Optional.empty(); + + private Optional description = Optional.empty(); + + private Optional namespace = Optional.empty(); + + private Optional name = Optional.empty(); + + private Optional id = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DetectConfigV2 other) { + id(other.getId()); + name(other.getName()); + namespace(other.getNamespace()); + description(other.getDescription()); + vaultId(other.getVaultId()); + vaultType(other.getVaultType()); + detect(other.getDetect()); + fileMapping(other.getFileMapping()); + media(other.getMedia()); + return this; + } + + /** + *

ID of the vault.

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

Mappings for source and deidentified file locations.

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

Mappings for source and deidentified file locations.

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

Type of the vault.

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

Type of the vault.

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

Description of the configuration.

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

Description of the configuration.

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

Namespace of the configuration.

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

Namespace of the configuration.

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

Name of the configuration.

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

Name of the configuration.

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

ID of the configuration.

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

ID of the configuration.

+ */ + @java.lang.Override + @JsonSetter(value = "ID", nulls = Nulls.SKIP) + public _FinalStage id(Optional id) { + this.id = id; + return this; + } + + @java.lang.Override + public DetectConfigV2 build() { + return new DetectConfigV2( + id, + name, + namespace, + description, + vaultId, + vaultType, + detect, + fileMapping, + media, + additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectConfigV2VaultType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectConfigV2VaultType.java new file mode 100644 index 00000000..4249b6a3 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectConfigV2VaultType.java @@ -0,0 +1,105 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectConfigV2VaultType { + public static final DetectConfigV2VaultType PRIVACYDB = new DetectConfigV2VaultType(Value.PRIVACYDB, "PRIVACYDB"); + + public static final DetectConfigV2VaultType FLOWDB = new DetectConfigV2VaultType(Value.FLOWDB, "FLOWDB"); + + public static final DetectConfigV2VaultType NONE = new DetectConfigV2VaultType(Value.NONE, "NONE"); + + public static final DetectConfigV2VaultType FLOWDB_SCHEMALESS = + new DetectConfigV2VaultType(Value.FLOWDB_SCHEMALESS, "FLOWDB_SCHEMALESS"); + + private final Value value; + + private final String string; + + DetectConfigV2VaultType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectConfigV2VaultType + && this.string.equals(((DetectConfigV2VaultType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case PRIVACYDB: + return visitor.visitPrivacydb(); + case FLOWDB: + return visitor.visitFlowdb(); + case NONE: + return visitor.visitNone(); + case FLOWDB_SCHEMALESS: + return visitor.visitFlowdbSchemaless(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectConfigV2VaultType valueOf(String value) { + switch (value) { + case "PRIVACYDB": + return PRIVACYDB; + case "FLOWDB": + return FLOWDB; + case "NONE": + return NONE; + case "FLOWDB_SCHEMALESS": + return FLOWDB_SCHEMALESS; + default: + return new DetectConfigV2VaultType(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + PRIVACYDB, + + FLOWDB, + + FLOWDB_SCHEMALESS, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitPrivacydb(); + + T visitFlowdb(); + + T visitFlowdbSchemaless(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectCustomTypes.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectCustomTypes.java new file mode 100644 index 00000000..a4db8e7c --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectCustomTypes.java @@ -0,0 +1,141 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectCustomTypes.Builder.class) +public final class DetectCustomTypes { + private final Optional label; + + private final Optional> match; + + private final Map additionalProperties; + + private DetectCustomTypes( + Optional label, Optional> match, Map additionalProperties) { + this.label = label; + this.match = match; + this.additionalProperties = additionalProperties; + } + + /** + * @return Label of the custom type. Note: Vault tokens are currently not supported. + */ + @JsonProperty("label") + public Optional getLabel() { + return label; + } + + /** + * @return Regular expressions to replace with '[<customType.label>]' enclosed in square brackets. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be redacted. Expressions don't match across entity boundaries. If a string or entity matches both skip and customType.label, the entity is displayed in plaintext. If a string is detected as an entity and a customType.match pattern matches the entire detected entity, the entity is replaced with '[<customType.label>]'. If a string is detected as an entity but a customType.match pattern only matches a substring of it, the customType.match pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. + */ + @JsonProperty("match") + public Optional> getMatch() { + return match; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectCustomTypes && equalTo((DetectCustomTypes) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectCustomTypes other) { + return label.equals(other.label) && match.equals(other.match); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.label, this.match); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional label = Optional.empty(); + + private Optional> match = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetectCustomTypes other) { + label(other.getLabel()); + match(other.getMatch()); + return this; + } + + /** + *

Label of the custom type. Note: Vault tokens are currently not supported.

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

Regular expressions to replace with '[<customType.label>]' enclosed in square brackets. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be redacted. Expressions don't match across entity boundaries. If a string or entity matches both skip and customType.label, the entity is displayed in plaintext. If a string is detected as an entity and a customType.match pattern matches the entire detected entity, the entity is replaced with '[<customType.label>]'. If a string is detected as an entity but a customType.match pattern only matches a substring of it, the customType.match pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

+ */ + @JsonSetter(value = "match", nulls = Nulls.SKIP) + public Builder match(Optional> match) { + this.match = match; + return this; + } + + public Builder match(List match) { + this.match = Optional.ofNullable(match); + return this; + } + + public DetectCustomTypes build() { + return new DetectCustomTypes(label, match, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntity.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntity.java new file mode 100644 index 00000000..472e7044 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntity.java @@ -0,0 +1,198 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectEntity.Builder.class) +public final class DetectEntity { + private final Optional entityType; + + private final Optional deidentificationType; + + private final Optional destination; + + private final Optional transformation; + + private final Map additionalProperties; + + private DetectEntity( + Optional entityType, + Optional deidentificationType, + Optional destination, + Optional transformation, + Map additionalProperties) { + this.entityType = entityType; + this.deidentificationType = deidentificationType; + this.destination = destination; + this.transformation = transformation; + this.additionalProperties = additionalProperties; + } + + /** + * @return Type of entity to detect. + */ + @JsonProperty("entityType") + public Optional getEntityType() { + return entityType; + } + + /** + * @return Type of deidentification to apply. VAULT_TOKEN is only supported for the following file formats: txt, json, csv, xml, jsonl, docx, xlsx, pptx. + */ + @JsonProperty("deidentificationType") + public Optional getDeidentificationType() { + return deidentificationType; + } + + /** + * @return Vault destination where detected values of this entity type are stored. For vaults with a schema, specify the table and column in table.column format (for example, persons.name). For schemaless vaults, specify the token group name (for example, personTokenGroup). + */ + @JsonProperty("destination") + public Optional getDestination() { + return destination; + } + + @JsonProperty("transformation") + public Optional getTransformation() { + return transformation; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectEntity && equalTo((DetectEntity) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectEntity other) { + return entityType.equals(other.entityType) + && deidentificationType.equals(other.deidentificationType) + && destination.equals(other.destination) + && transformation.equals(other.transformation); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.entityType, this.deidentificationType, this.destination, this.transformation); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional entityType = Optional.empty(); + + private Optional deidentificationType = Optional.empty(); + + private Optional destination = Optional.empty(); + + private Optional transformation = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetectEntity other) { + entityType(other.getEntityType()); + deidentificationType(other.getDeidentificationType()); + destination(other.getDestination()); + transformation(other.getTransformation()); + return this; + } + + /** + *

Type of entity to detect.

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

Type of deidentification to apply. VAULT_TOKEN is only supported for the following file formats: txt, json, csv, xml, jsonl, docx, xlsx, pptx.

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

Vault destination where detected values of this entity type are stored. For vaults with a schema, specify the table and column in table.column format (for example, persons.name). For schemaless vaults, specify the token group name (for example, personTokenGroup).

+ */ + @JsonSetter(value = "destination", nulls = Nulls.SKIP) + public Builder destination(Optional destination) { + this.destination = destination; + return this; + } + + public Builder destination(String destination) { + this.destination = Optional.ofNullable(destination); + return this; + } + + @JsonSetter(value = "transformation", nulls = Nulls.SKIP) + public Builder transformation(Optional transformation) { + this.transformation = transformation; + return this; + } + + public Builder transformation(EntityTransformation transformation) { + this.transformation = Optional.ofNullable(transformation); + return this; + } + + public DetectEntity build() { + return new DetectEntity( + entityType, deidentificationType, destination, transformation, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntityDeidentificationType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntityDeidentificationType.java new file mode 100644 index 00000000..26262dce --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntityDeidentificationType.java @@ -0,0 +1,119 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectEntityDeidentificationType { + public static final DetectEntityDeidentificationType MASK = + new DetectEntityDeidentificationType(Value.MASK, "MASK"); + + public static final DetectEntityDeidentificationType ENTITY_ONLY = + new DetectEntityDeidentificationType(Value.ENTITY_ONLY, "ENTITY_ONLY"); + + public static final DetectEntityDeidentificationType VAULT_TOKEN = + new DetectEntityDeidentificationType(Value.VAULT_TOKEN, "VAULT_TOKEN"); + + public static final DetectEntityDeidentificationType UNKNOWN = + new DetectEntityDeidentificationType(Value.UNKNOWN, "UNKNOWN"); + + public static final DetectEntityDeidentificationType ENTITY_UNIQUE_COUNTER = + new DetectEntityDeidentificationType(Value.ENTITY_UNIQUE_COUNTER, "ENTITY_UNIQUE_COUNTER"); + + private final Value value; + + private final String string; + + DetectEntityDeidentificationType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectEntityDeidentificationType + && this.string.equals(((DetectEntityDeidentificationType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case MASK: + return visitor.visitMask(); + case ENTITY_ONLY: + return visitor.visitEntityOnly(); + case VAULT_TOKEN: + return visitor.visitVaultToken(); + case UNKNOWN: + return visitor.visitUnknown(); + case ENTITY_UNIQUE_COUNTER: + return visitor.visitEntityUniqueCounter(); + case _UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectEntityDeidentificationType valueOf(String value) { + switch (value) { + case "MASK": + return MASK; + case "ENTITY_ONLY": + return ENTITY_ONLY; + case "VAULT_TOKEN": + return VAULT_TOKEN; + case "UNKNOWN": + return UNKNOWN; + case "ENTITY_UNIQUE_COUNTER": + return ENTITY_UNIQUE_COUNTER; + default: + return new DetectEntityDeidentificationType(Value._UNKNOWN, value); + } + } + + public enum Value { + UNKNOWN, + + ENTITY_UNIQUE_COUNTER, + + ENTITY_ONLY, + + VAULT_TOKEN, + + MASK, + + _UNKNOWN + } + + public interface Visitor { + T visitUnknown(); + + T visitEntityUniqueCounter(); + + T visitEntityOnly(); + + T visitVaultToken(); + + T visitMask(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntityEntityType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntityEntityType.java new file mode 100644 index 00000000..7e286cfc --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectEntityEntityType.java @@ -0,0 +1,806 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectEntityEntityType { + public static final DetectEntityEntityType PHONE_NUMBER = + new DetectEntityEntityType(Value.PHONE_NUMBER, "PHONE_NUMBER"); + + public static final DetectEntityEntityType USERNAME = new DetectEntityEntityType(Value.USERNAME, "USERNAME"); + + public static final DetectEntityEntityType VEHICLE_ID = new DetectEntityEntityType(Value.VEHICLE_ID, "VEHICLE_ID"); + + public static final DetectEntityEntityType RELIGION = new DetectEntityEntityType(Value.RELIGION, "RELIGION"); + + public static final DetectEntityEntityType ORIGIN = new DetectEntityEntityType(Value.ORIGIN, "ORIGIN"); + + public static final DetectEntityEntityType PASSPORT_NUMBER = + new DetectEntityEntityType(Value.PASSPORT_NUMBER, "PASSPORT_NUMBER"); + + public static final DetectEntityEntityType YEAR = new DetectEntityEntityType(Value.YEAR, "YEAR"); + + public static final DetectEntityEntityType CONDITION = new DetectEntityEntityType(Value.CONDITION, "CONDITION"); + + public static final DetectEntityEntityType LOCATION = new DetectEntityEntityType(Value.LOCATION, "LOCATION"); + + public static final DetectEntityEntityType LOCATION_CITY = + new DetectEntityEntityType(Value.LOCATION_CITY, "LOCATION_CITY"); + + public static final DetectEntityEntityType LOCATION_COUNTRY = + new DetectEntityEntityType(Value.LOCATION_COUNTRY, "LOCATION_COUNTRY"); + + public static final DetectEntityEntityType PROJECT = new DetectEntityEntityType(Value.PROJECT, "PROJECT"); + + public static final DetectEntityEntityType LOCATION_ZIP = + new DetectEntityEntityType(Value.LOCATION_ZIP, "LOCATION_ZIP"); + + public static final DetectEntityEntityType NAME_MEDICAL_PROFESSIONAL = + new DetectEntityEntityType(Value.NAME_MEDICAL_PROFESSIONAL, "NAME_MEDICAL_PROFESSIONAL"); + + public static final DetectEntityEntityType BANK_ACCOUNT = + new DetectEntityEntityType(Value.BANK_ACCOUNT, "BANK_ACCOUNT"); + + public static final DetectEntityEntityType OCCUPATION = new DetectEntityEntityType(Value.OCCUPATION, "OCCUPATION"); + + public static final DetectEntityEntityType TIME = new DetectEntityEntityType(Value.TIME, "TIME"); + + public static final DetectEntityEntityType LOCATION_STATE = + new DetectEntityEntityType(Value.LOCATION_STATE, "LOCATION_STATE"); + + public static final DetectEntityEntityType EVENT = new DetectEntityEntityType(Value.EVENT, "EVENT"); + + public static final DetectEntityEntityType POLITICAL_AFFILIATION = + new DetectEntityEntityType(Value.POLITICAL_AFFILIATION, "POLITICAL_AFFILIATION"); + + public static final DetectEntityEntityType LANGUAGE = new DetectEntityEntityType(Value.LANGUAGE, "LANGUAGE"); + + public static final DetectEntityEntityType ZODIAC_SIGN = + new DetectEntityEntityType(Value.ZODIAC_SIGN, "ZODIAC_SIGN"); + + public static final DetectEntityEntityType PRODUCT = new DetectEntityEntityType(Value.PRODUCT, "PRODUCT"); + + public static final DetectEntityEntityType SEXUALITY = new DetectEntityEntityType(Value.SEXUALITY, "SEXUALITY"); + + public static final DetectEntityEntityType DURATION = new DetectEntityEntityType(Value.DURATION, "DURATION"); + + public static final DetectEntityEntityType PHYSICAL_ATTRIBUTE = + new DetectEntityEntityType(Value.PHYSICAL_ATTRIBUTE, "PHYSICAL_ATTRIBUTE"); + + public static final DetectEntityEntityType LOCATION_ADDRESS_STREET = + new DetectEntityEntityType(Value.LOCATION_ADDRESS_STREET, "LOCATION_ADDRESS_STREET"); + + public static final DetectEntityEntityType MEDICAL_PROCESS = + new DetectEntityEntityType(Value.MEDICAL_PROCESS, "MEDICAL_PROCESS"); + + public static final DetectEntityEntityType LOCATION_ADDRESS = + new DetectEntityEntityType(Value.LOCATION_ADDRESS, "LOCATION_ADDRESS"); + + public static final DetectEntityEntityType FILENAME = new DetectEntityEntityType(Value.FILENAME, "FILENAME"); + + public static final DetectEntityEntityType DOB = new DetectEntityEntityType(Value.DOB, "DOB"); + + public static final DetectEntityEntityType ORGANIZATION_MEDICAL_FACILITY = + new DetectEntityEntityType(Value.ORGANIZATION_MEDICAL_FACILITY, "ORGANIZATION_MEDICAL_FACILITY"); + + public static final DetectEntityEntityType ROUTING_NUMBER = + new DetectEntityEntityType(Value.ROUTING_NUMBER, "ROUTING_NUMBER"); + + public static final DetectEntityEntityType HEALTHCARE_NUMBER = + new DetectEntityEntityType(Value.HEALTHCARE_NUMBER, "HEALTHCARE_NUMBER"); + + public static final DetectEntityEntityType GENDER = new DetectEntityEntityType(Value.GENDER, "GENDER"); + + public static final DetectEntityEntityType NAME = new DetectEntityEntityType(Value.NAME, "NAME"); + + public static final DetectEntityEntityType DRUG = new DetectEntityEntityType(Value.DRUG, "DRUG"); + + public static final DetectEntityEntityType NONE = new DetectEntityEntityType(Value.NONE, "NONE"); + + public static final DetectEntityEntityType DATE_INTERVAL = + new DetectEntityEntityType(Value.DATE_INTERVAL, "DATE_INTERVAL"); + + public static final DetectEntityEntityType MARITAL_STATUS = + new DetectEntityEntityType(Value.MARITAL_STATUS, "MARITAL_STATUS"); + + public static final DetectEntityEntityType CORPORATE_ACTION = + new DetectEntityEntityType(Value.CORPORATE_ACTION, "CORPORATE_ACTION"); + + public static final DetectEntityEntityType AGE = new DetectEntityEntityType(Value.AGE, "AGE"); + + public static final DetectEntityEntityType CVV = new DetectEntityEntityType(Value.CVV, "CVV"); + + public static final DetectEntityEntityType NAME_GIVEN = new DetectEntityEntityType(Value.NAME_GIVEN, "NAME_GIVEN"); + + public static final DetectEntityEntityType DATE = new DetectEntityEntityType(Value.DATE, "DATE"); + + public static final DetectEntityEntityType DAY = new DetectEntityEntityType(Value.DAY, "DAY"); + + public static final DetectEntityEntityType EFFECT = new DetectEntityEntityType(Value.EFFECT, "EFFECT"); + + public static final DetectEntityEntityType MEDICAL_CODE = + new DetectEntityEntityType(Value.MEDICAL_CODE, "MEDICAL_CODE"); + + public static final DetectEntityEntityType NUMERICAL_PII = + new DetectEntityEntityType(Value.NUMERICAL_PII, "NUMERICAL_PII"); + + public static final DetectEntityEntityType TREND = new DetectEntityEntityType(Value.TREND, "TREND"); + + public static final DetectEntityEntityType INJURY = new DetectEntityEntityType(Value.INJURY, "INJURY"); + + public static final DetectEntityEntityType DRIVER_LICENSE = + new DetectEntityEntityType(Value.DRIVER_LICENSE, "DRIVER_LICENSE"); + + public static final DetectEntityEntityType ALL = new DetectEntityEntityType(Value.ALL, "ALL"); + + public static final DetectEntityEntityType ORGANIZATION_ID = + new DetectEntityEntityType(Value.ORGANIZATION_ID, "ORGANIZATION_ID"); + + public static final DetectEntityEntityType PASSWORD = new DetectEntityEntityType(Value.PASSWORD, "PASSWORD"); + + public static final DetectEntityEntityType DOSE = new DetectEntityEntityType(Value.DOSE, "DOSE"); + + public static final DetectEntityEntityType NAME_FAMILY = + new DetectEntityEntityType(Value.NAME_FAMILY, "NAME_FAMILY"); + + public static final DetectEntityEntityType MONEY = new DetectEntityEntityType(Value.MONEY, "MONEY"); + + public static final DetectEntityEntityType URL = new DetectEntityEntityType(Value.URL, "URL"); + + public static final DetectEntityEntityType LOCATION_COORDINATE = + new DetectEntityEntityType(Value.LOCATION_COORDINATE, "LOCATION_COORDINATE"); + + public static final DetectEntityEntityType FINANCIAL_METRIC = + new DetectEntityEntityType(Value.FINANCIAL_METRIC, "FINANCIAL_METRIC"); + + public static final DetectEntityEntityType ORGANIZATION = + new DetectEntityEntityType(Value.ORGANIZATION, "ORGANIZATION"); + + public static final DetectEntityEntityType IP_ADDRESS = new DetectEntityEntityType(Value.IP_ADDRESS, "IP_ADDRESS"); + + public static final DetectEntityEntityType BLOOD_TYPE = new DetectEntityEntityType(Value.BLOOD_TYPE, "BLOOD_TYPE"); + + public static final DetectEntityEntityType MONTH = new DetectEntityEntityType(Value.MONTH, "MONTH"); + + public static final DetectEntityEntityType CREDIT_CARD = + new DetectEntityEntityType(Value.CREDIT_CARD, "CREDIT_CARD"); + + public static final DetectEntityEntityType ACCOUNT_NUMBER = + new DetectEntityEntityType(Value.ACCOUNT_NUMBER, "ACCOUNT_NUMBER"); + + public static final DetectEntityEntityType CREDIT_CARD_EXPIRATION = + new DetectEntityEntityType(Value.CREDIT_CARD_EXPIRATION, "CREDIT_CARD_EXPIRATION"); + + public static final DetectEntityEntityType SSN = new DetectEntityEntityType(Value.SSN, "SSN"); + + public static final DetectEntityEntityType EMAIL_ADDRESS = + new DetectEntityEntityType(Value.EMAIL_ADDRESS, "EMAIL_ADDRESS"); + + public static final DetectEntityEntityType STATISTICS = new DetectEntityEntityType(Value.STATISTICS, "STATISTICS"); + + private final Value value; + + private final String string; + + DetectEntityEntityType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectEntityEntityType + && this.string.equals(((DetectEntityEntityType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case PHONE_NUMBER: + return visitor.visitPhoneNumber(); + case USERNAME: + return visitor.visitUsername(); + case VEHICLE_ID: + return visitor.visitVehicleId(); + case RELIGION: + return visitor.visitReligion(); + case ORIGIN: + return visitor.visitOrigin(); + case PASSPORT_NUMBER: + return visitor.visitPassportNumber(); + case YEAR: + return visitor.visitYear(); + case CONDITION: + return visitor.visitCondition(); + case LOCATION: + return visitor.visitLocation(); + case LOCATION_CITY: + return visitor.visitLocationCity(); + case LOCATION_COUNTRY: + return visitor.visitLocationCountry(); + case PROJECT: + return visitor.visitProject(); + case LOCATION_ZIP: + return visitor.visitLocationZip(); + case NAME_MEDICAL_PROFESSIONAL: + return visitor.visitNameMedicalProfessional(); + case BANK_ACCOUNT: + return visitor.visitBankAccount(); + case OCCUPATION: + return visitor.visitOccupation(); + case TIME: + return visitor.visitTime(); + case LOCATION_STATE: + return visitor.visitLocationState(); + case EVENT: + return visitor.visitEvent(); + case POLITICAL_AFFILIATION: + return visitor.visitPoliticalAffiliation(); + case LANGUAGE: + return visitor.visitLanguage(); + case ZODIAC_SIGN: + return visitor.visitZodiacSign(); + case PRODUCT: + return visitor.visitProduct(); + case SEXUALITY: + return visitor.visitSexuality(); + case DURATION: + return visitor.visitDuration(); + case PHYSICAL_ATTRIBUTE: + return visitor.visitPhysicalAttribute(); + case LOCATION_ADDRESS_STREET: + return visitor.visitLocationAddressStreet(); + case MEDICAL_PROCESS: + return visitor.visitMedicalProcess(); + case LOCATION_ADDRESS: + return visitor.visitLocationAddress(); + case FILENAME: + return visitor.visitFilename(); + case DOB: + return visitor.visitDob(); + case ORGANIZATION_MEDICAL_FACILITY: + return visitor.visitOrganizationMedicalFacility(); + case ROUTING_NUMBER: + return visitor.visitRoutingNumber(); + case HEALTHCARE_NUMBER: + return visitor.visitHealthcareNumber(); + case GENDER: + return visitor.visitGender(); + case NAME: + return visitor.visitName(); + case DRUG: + return visitor.visitDrug(); + case NONE: + return visitor.visitNone(); + case DATE_INTERVAL: + return visitor.visitDateInterval(); + case MARITAL_STATUS: + return visitor.visitMaritalStatus(); + case CORPORATE_ACTION: + return visitor.visitCorporateAction(); + case AGE: + return visitor.visitAge(); + case CVV: + return visitor.visitCvv(); + case NAME_GIVEN: + return visitor.visitNameGiven(); + case DATE: + return visitor.visitDate(); + case DAY: + return visitor.visitDay(); + case EFFECT: + return visitor.visitEffect(); + case MEDICAL_CODE: + return visitor.visitMedicalCode(); + case NUMERICAL_PII: + return visitor.visitNumericalPii(); + case TREND: + return visitor.visitTrend(); + case INJURY: + return visitor.visitInjury(); + case DRIVER_LICENSE: + return visitor.visitDriverLicense(); + case ALL: + return visitor.visitAll(); + case ORGANIZATION_ID: + return visitor.visitOrganizationId(); + case PASSWORD: + return visitor.visitPassword(); + case DOSE: + return visitor.visitDose(); + case NAME_FAMILY: + return visitor.visitNameFamily(); + case MONEY: + return visitor.visitMoney(); + case URL: + return visitor.visitUrl(); + case LOCATION_COORDINATE: + return visitor.visitLocationCoordinate(); + case FINANCIAL_METRIC: + return visitor.visitFinancialMetric(); + case ORGANIZATION: + return visitor.visitOrganization(); + case IP_ADDRESS: + return visitor.visitIpAddress(); + case BLOOD_TYPE: + return visitor.visitBloodType(); + case MONTH: + return visitor.visitMonth(); + case CREDIT_CARD: + return visitor.visitCreditCard(); + case ACCOUNT_NUMBER: + return visitor.visitAccountNumber(); + case CREDIT_CARD_EXPIRATION: + return visitor.visitCreditCardExpiration(); + case SSN: + return visitor.visitSsn(); + case EMAIL_ADDRESS: + return visitor.visitEmailAddress(); + case STATISTICS: + return visitor.visitStatistics(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectEntityEntityType valueOf(String value) { + switch (value) { + case "PHONE_NUMBER": + return PHONE_NUMBER; + case "USERNAME": + return USERNAME; + case "VEHICLE_ID": + return VEHICLE_ID; + case "RELIGION": + return RELIGION; + case "ORIGIN": + return ORIGIN; + case "PASSPORT_NUMBER": + return PASSPORT_NUMBER; + case "YEAR": + return YEAR; + case "CONDITION": + return CONDITION; + case "LOCATION": + return LOCATION; + case "LOCATION_CITY": + return LOCATION_CITY; + case "LOCATION_COUNTRY": + return LOCATION_COUNTRY; + case "PROJECT": + return PROJECT; + case "LOCATION_ZIP": + return LOCATION_ZIP; + case "NAME_MEDICAL_PROFESSIONAL": + return NAME_MEDICAL_PROFESSIONAL; + case "BANK_ACCOUNT": + return BANK_ACCOUNT; + case "OCCUPATION": + return OCCUPATION; + case "TIME": + return TIME; + case "LOCATION_STATE": + return LOCATION_STATE; + case "EVENT": + return EVENT; + case "POLITICAL_AFFILIATION": + return POLITICAL_AFFILIATION; + case "LANGUAGE": + return LANGUAGE; + case "ZODIAC_SIGN": + return ZODIAC_SIGN; + case "PRODUCT": + return PRODUCT; + case "SEXUALITY": + return SEXUALITY; + case "DURATION": + return DURATION; + case "PHYSICAL_ATTRIBUTE": + return PHYSICAL_ATTRIBUTE; + case "LOCATION_ADDRESS_STREET": + return LOCATION_ADDRESS_STREET; + case "MEDICAL_PROCESS": + return MEDICAL_PROCESS; + case "LOCATION_ADDRESS": + return LOCATION_ADDRESS; + case "FILENAME": + return FILENAME; + case "DOB": + return DOB; + case "ORGANIZATION_MEDICAL_FACILITY": + return ORGANIZATION_MEDICAL_FACILITY; + case "ROUTING_NUMBER": + return ROUTING_NUMBER; + case "HEALTHCARE_NUMBER": + return HEALTHCARE_NUMBER; + case "GENDER": + return GENDER; + case "NAME": + return NAME; + case "DRUG": + return DRUG; + case "NONE": + return NONE; + case "DATE_INTERVAL": + return DATE_INTERVAL; + case "MARITAL_STATUS": + return MARITAL_STATUS; + case "CORPORATE_ACTION": + return CORPORATE_ACTION; + case "AGE": + return AGE; + case "CVV": + return CVV; + case "NAME_GIVEN": + return NAME_GIVEN; + case "DATE": + return DATE; + case "DAY": + return DAY; + case "EFFECT": + return EFFECT; + case "MEDICAL_CODE": + return MEDICAL_CODE; + case "NUMERICAL_PII": + return NUMERICAL_PII; + case "TREND": + return TREND; + case "INJURY": + return INJURY; + case "DRIVER_LICENSE": + return DRIVER_LICENSE; + case "ALL": + return ALL; + case "ORGANIZATION_ID": + return ORGANIZATION_ID; + case "PASSWORD": + return PASSWORD; + case "DOSE": + return DOSE; + case "NAME_FAMILY": + return NAME_FAMILY; + case "MONEY": + return MONEY; + case "URL": + return URL; + case "LOCATION_COORDINATE": + return LOCATION_COORDINATE; + case "FINANCIAL_METRIC": + return FINANCIAL_METRIC; + case "ORGANIZATION": + return ORGANIZATION; + case "IP_ADDRESS": + return IP_ADDRESS; + case "BLOOD_TYPE": + return BLOOD_TYPE; + case "MONTH": + return MONTH; + case "CREDIT_CARD": + return CREDIT_CARD; + case "ACCOUNT_NUMBER": + return ACCOUNT_NUMBER; + case "CREDIT_CARD_EXPIRATION": + return CREDIT_CARD_EXPIRATION; + case "SSN": + return SSN; + case "EMAIL_ADDRESS": + return EMAIL_ADDRESS; + case "STATISTICS": + return STATISTICS; + default: + return new DetectEntityEntityType(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + BANK_ACCOUNT, + + CREDIT_CARD, + + CREDIT_CARD_EXPIRATION, + + CVV, + + DATE, + + DATE_INTERVAL, + + DOB, + + DRIVER_LICENSE, + + EMAIL_ADDRESS, + + HEALTHCARE_NUMBER, + + IP_ADDRESS, + + LOCATION, + + NAME, + + NUMERICAL_PII, + + PHONE_NUMBER, + + SSN, + + URL, + + VEHICLE_ID, + + MEDICAL_CODE, + + NAME_FAMILY, + + NAME_GIVEN, + + ACCOUNT_NUMBER, + + EVENT, + + FILENAME, + + GENDER, + + LANGUAGE, + + LOCATION_ADDRESS, + + LOCATION_CITY, + + LOCATION_COORDINATE, + + LOCATION_COUNTRY, + + LOCATION_STATE, + + LOCATION_ZIP, + + MARITAL_STATUS, + + MONEY, + + NAME_MEDICAL_PROFESSIONAL, + + OCCUPATION, + + ORGANIZATION, + + ORGANIZATION_MEDICAL_FACILITY, + + ORIGIN, + + PASSPORT_NUMBER, + + PASSWORD, + + PHYSICAL_ATTRIBUTE, + + POLITICAL_AFFILIATION, + + RELIGION, + + TIME, + + USERNAME, + + ZODIAC_SIGN, + + BLOOD_TYPE, + + CONDITION, + + DOSE, + + DRUG, + + INJURY, + + MEDICAL_PROCESS, + + STATISTICS, + + ROUTING_NUMBER, + + CORPORATE_ACTION, + + FINANCIAL_METRIC, + + PRODUCT, + + TREND, + + DURATION, + + LOCATION_ADDRESS_STREET, + + AGE, + + SEXUALITY, + + EFFECT, + + PROJECT, + + ORGANIZATION_ID, + + DAY, + + MONTH, + + YEAR, + + ALL, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitBankAccount(); + + T visitCreditCard(); + + T visitCreditCardExpiration(); + + T visitCvv(); + + T visitDate(); + + T visitDateInterval(); + + T visitDob(); + + T visitDriverLicense(); + + T visitEmailAddress(); + + T visitHealthcareNumber(); + + T visitIpAddress(); + + T visitLocation(); + + T visitName(); + + T visitNumericalPii(); + + T visitPhoneNumber(); + + T visitSsn(); + + T visitUrl(); + + T visitVehicleId(); + + T visitMedicalCode(); + + T visitNameFamily(); + + T visitNameGiven(); + + T visitAccountNumber(); + + T visitEvent(); + + T visitFilename(); + + T visitGender(); + + T visitLanguage(); + + T visitLocationAddress(); + + T visitLocationCity(); + + T visitLocationCoordinate(); + + T visitLocationCountry(); + + T visitLocationState(); + + T visitLocationZip(); + + T visitMaritalStatus(); + + T visitMoney(); + + T visitNameMedicalProfessional(); + + T visitOccupation(); + + T visitOrganization(); + + T visitOrganizationMedicalFacility(); + + T visitOrigin(); + + T visitPassportNumber(); + + T visitPassword(); + + T visitPhysicalAttribute(); + + T visitPoliticalAffiliation(); + + T visitReligion(); + + T visitTime(); + + T visitUsername(); + + T visitZodiacSign(); + + T visitBloodType(); + + T visitCondition(); + + T visitDose(); + + T visitDrug(); + + T visitInjury(); + + T visitMedicalProcess(); + + T visitStatistics(); + + T visitRoutingNumber(); + + T visitCorporateAction(); + + T visitFinancialMetric(); + + T visitProduct(); + + T visitTrend(); + + T visitDuration(); + + T visitLocationAddressStreet(); + + T visitAge(); + + T visitSexuality(); + + T visitEffect(); + + T visitProject(); + + T visitOrganizationId(); + + T visitDay(); + + T visitMonth(); + + T visitYear(); + + T visitAll(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectGuardrailsResponse.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectGuardrailsResponseV2.java similarity index 66% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/DetectGuardrailsResponse.java rename to common/src/main/java/com/skyflow/generated/detect/rest/types/DetectGuardrailsResponseV2.java index 9cb2d319..ca14dc32 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectGuardrailsResponse.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectGuardrailsResponseV2.java @@ -1,36 +1,41 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import org.jetbrains.annotations.NotNull; - +import com.skyflow.generated.detect.rest.core.ObjectMappers; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; +import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DetectGuardrailsResponse.Builder.class) -public final class DetectGuardrailsResponse { +@JsonDeserialize(builder = DetectGuardrailsResponseV2.Builder.class) +public final class DetectGuardrailsResponseV2 { private final String text; private final Optional toxic; private final Optional deniedTopic; - private final DetectGuardrailsResponseValidation validation; + private final DetectGuardrailsResponseV2Validation validation; private final Map additionalProperties; - private DetectGuardrailsResponse( + private DetectGuardrailsResponseV2( String text, Optional toxic, Optional deniedTopic, - DetectGuardrailsResponseValidation validation, + DetectGuardrailsResponseV2Validation validation, Map additionalProperties) { this.text = text; this.toxic = toxic; @@ -58,7 +63,7 @@ public Optional getToxic() { /** * @return Whether the text included a denied topic. */ - @JsonProperty("denied_topic") + @JsonProperty("deniedTopic") public Optional getDeniedTopic() { return deniedTopic; } @@ -67,14 +72,14 @@ public Optional getDeniedTopic() { * @return Whether the text passed validation. */ @JsonProperty("validation") - public DetectGuardrailsResponseValidation getValidation() { + public DetectGuardrailsResponseV2Validation getValidation() { return validation; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof DetectGuardrailsResponse && equalTo((DetectGuardrailsResponse) other); + return other instanceof DetectGuardrailsResponseV2 && equalTo((DetectGuardrailsResponseV2) other); } @JsonAnyGetter @@ -82,19 +87,19 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(DetectGuardrailsResponse other) { + private boolean equalTo(DetectGuardrailsResponseV2 other) { return text.equals(other.text) && toxic.equals(other.toxic) && deniedTopic.equals(other.deniedTopic) && validation.equals(other.validation); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.text, this.toxic, this.deniedTopic, this.validation); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -105,22 +110,26 @@ public static TextStage builder() { public interface TextStage { /** - * Text that was checked against guardrails. + *

Text that was checked against guardrails.

*/ ValidationStage text(@NotNull String text); - Builder from(DetectGuardrailsResponse other); + Builder from(DetectGuardrailsResponseV2 other); } public interface ValidationStage { /** - * Whether the text passed validation. + *

Whether the text passed validation.

*/ - _FinalStage validation(@NotNull DetectGuardrailsResponseValidation validation); + _FinalStage validation(@NotNull DetectGuardrailsResponseV2Validation validation); } public interface _FinalStage { - DetectGuardrailsResponse build(); + DetectGuardrailsResponseV2 build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); /** *

Whether the text is toxic.

@@ -141,7 +150,7 @@ public interface _FinalStage { public static final class Builder implements TextStage, ValidationStage, _FinalStage { private String text; - private DetectGuardrailsResponseValidation validation; + private DetectGuardrailsResponseV2Validation validation; private Optional deniedTopic = Optional.empty(); @@ -152,8 +161,8 @@ public static final class Builder implements TextStage, ValidationStage, _FinalS private Builder() {} - @Override - public Builder from(DetectGuardrailsResponse other) { + @java.lang.Override + public Builder from(DetectGuardrailsResponseV2 other) { text(other.getText()); toxic(other.getToxic()); deniedTopic(other.getDeniedTopic()); @@ -162,10 +171,10 @@ public Builder from(DetectGuardrailsResponse other) { } /** - * Text that was checked against guardrails.

Text that was checked against guardrails.

+ *

Text that was checked against guardrails.

* @return Reference to {@code this} so that method calls can be chained together. */ - @Override + @java.lang.Override @JsonSetter("text") public ValidationStage text(@NotNull String text) { this.text = Objects.requireNonNull(text, "text must not be null"); @@ -173,12 +182,12 @@ public ValidationStage text(@NotNull String text) { } /** - * Whether the text passed validation.

Whether the text passed validation.

+ *

Whether the text passed validation.

* @return Reference to {@code this} so that method calls can be chained together. */ - @Override + @java.lang.Override @JsonSetter("validation") - public _FinalStage validation(@NotNull DetectGuardrailsResponseValidation validation) { + public _FinalStage validation(@NotNull DetectGuardrailsResponseV2Validation validation) { this.validation = Objects.requireNonNull(validation, "validation must not be null"); return this; } @@ -187,7 +196,7 @@ public _FinalStage validation(@NotNull DetectGuardrailsResponseValidation valida *

Whether the text included a denied topic.

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

Whether the text included a denied topic.

*/ - @Override - @JsonSetter(value = "denied_topic", nulls = Nulls.SKIP) + @java.lang.Override + @JsonSetter(value = "deniedTopic", nulls = Nulls.SKIP) public _FinalStage deniedTopic(Optional deniedTopic) { this.deniedTopic = deniedTopic; return this; @@ -207,7 +216,7 @@ public _FinalStage deniedTopic(Optional deniedTopic) { *

Whether the text is toxic.

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

Whether the text is toxic.

*/ - @Override + @java.lang.Override @JsonSetter(value = "toxic", nulls = Nulls.SKIP) public _FinalStage toxic(Optional toxic) { this.toxic = toxic; return this; } - @Override - public DetectGuardrailsResponse build() { - return new DetectGuardrailsResponse(text, toxic, deniedTopic, validation, additionalProperties); + @java.lang.Override + public DetectGuardrailsResponseV2 build() { + return new DetectGuardrailsResponseV2(text, toxic, deniedTopic, validation, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectGuardrailsResponseV2Validation.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectGuardrailsResponseV2Validation.java new file mode 100644 index 00000000..0337a29f --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectGuardrailsResponseV2Validation.java @@ -0,0 +1,86 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectGuardrailsResponseV2Validation { + public static final DetectGuardrailsResponseV2Validation PASSED = + new DetectGuardrailsResponseV2Validation(Value.PASSED, "PASSED"); + + public static final DetectGuardrailsResponseV2Validation FAILED = + new DetectGuardrailsResponseV2Validation(Value.FAILED, "FAILED"); + + private final Value value; + + private final String string; + + DetectGuardrailsResponseV2Validation(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectGuardrailsResponseV2Validation + && this.string.equals(((DetectGuardrailsResponseV2Validation) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case PASSED: + return visitor.visitPassed(); + case FAILED: + return visitor.visitFailed(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectGuardrailsResponseV2Validation valueOf(String value) { + switch (value) { + case "PASSED": + return PASSED; + case "FAILED": + return FAILED; + default: + return new DetectGuardrailsResponseV2Validation(Value.UNKNOWN, value); + } + } + + public enum Value { + FAILED, + + PASSED, + + UNKNOWN + } + + public interface Visitor { + T visitFailed(); + + T visitPassed(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntity.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntity.java new file mode 100644 index 00000000..52333c00 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntity.java @@ -0,0 +1,142 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectObjectEntity.Builder.class) +public final class DetectObjectEntity { + private final Optional entityType; + + private final Optional deidentificationType; + + private final Map additionalProperties; + + private DetectObjectEntity( + Optional entityType, + Optional deidentificationType, + Map additionalProperties) { + this.entityType = entityType; + this.deidentificationType = deidentificationType; + this.additionalProperties = additionalProperties; + } + + /** + * @return Type of entity to detect. + */ + @JsonProperty("entityType") + public Optional getEntityType() { + return entityType; + } + + /** + * @return Type of deidentification to apply. + */ + @JsonProperty("deidentificationType") + public Optional getDeidentificationType() { + return deidentificationType; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectObjectEntity && equalTo((DetectObjectEntity) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectObjectEntity other) { + return entityType.equals(other.entityType) && deidentificationType.equals(other.deidentificationType); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.entityType, this.deidentificationType); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional entityType = Optional.empty(); + + private Optional deidentificationType = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetectObjectEntity other) { + entityType(other.getEntityType()); + deidentificationType(other.getDeidentificationType()); + return this; + } + + /** + *

Type of entity to detect.

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

Type of deidentification to apply.

+ */ + @JsonSetter(value = "deidentificationType", nulls = Nulls.SKIP) + public Builder deidentificationType(Optional deidentificationType) { + this.deidentificationType = deidentificationType; + return this; + } + + public Builder deidentificationType(DetectObjectEntityDeidentificationType deidentificationType) { + this.deidentificationType = Optional.ofNullable(deidentificationType); + return this; + } + + public DetectObjectEntity build() { + return new DetectObjectEntity(entityType, deidentificationType, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntityDeidentificationType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntityDeidentificationType.java new file mode 100644 index 00000000..aec7dc98 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntityDeidentificationType.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectObjectEntityDeidentificationType { + public static final DetectObjectEntityDeidentificationType UNREDACT = + new DetectObjectEntityDeidentificationType(Value.UNREDACT, "UNREDACT"); + + public static final DetectObjectEntityDeidentificationType UNKNOWN = + new DetectObjectEntityDeidentificationType(Value.UNKNOWN, "UNKNOWN"); + + public static final DetectObjectEntityDeidentificationType REDACT = + new DetectObjectEntityDeidentificationType(Value.REDACT, "REDACT"); + + private final Value value; + + private final String string; + + DetectObjectEntityDeidentificationType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectObjectEntityDeidentificationType + && this.string.equals(((DetectObjectEntityDeidentificationType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case UNREDACT: + return visitor.visitUnredact(); + case UNKNOWN: + return visitor.visitUnknown(); + case REDACT: + return visitor.visitRedact(); + case _UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectObjectEntityDeidentificationType valueOf(String value) { + switch (value) { + case "UNREDACT": + return UNREDACT; + case "UNKNOWN": + return UNKNOWN; + case "REDACT": + return REDACT; + default: + return new DetectObjectEntityDeidentificationType(Value._UNKNOWN, value); + } + } + + public enum Value { + UNKNOWN, + + REDACT, + + UNREDACT, + + _UNKNOWN + } + + public interface Visitor { + T visitUnknown(); + + T visitRedact(); + + T visitUnredact(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntityEntityType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntityEntityType.java new file mode 100644 index 00000000..93f8b64f --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectObjectEntityEntityType.java @@ -0,0 +1,126 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectObjectEntityEntityType { + public static final DetectObjectEntityEntityType FACE = new DetectObjectEntityEntityType(Value.FACE, "FACE"); + + public static final DetectObjectEntityEntityType SIGNATURE = + new DetectObjectEntityEntityType(Value.SIGNATURE, "SIGNATURE"); + + public static final DetectObjectEntityEntityType LICENSE_PLATE = + new DetectObjectEntityEntityType(Value.LICENSE_PLATE, "LICENSE_PLATE"); + + public static final DetectObjectEntityEntityType ALL = new DetectObjectEntityEntityType(Value.ALL, "ALL"); + + public static final DetectObjectEntityEntityType NONE = new DetectObjectEntityEntityType(Value.NONE, "NONE"); + + public static final DetectObjectEntityEntityType LOGO = new DetectObjectEntityEntityType(Value.LOGO, "LOGO"); + + private final Value value; + + private final String string; + + DetectObjectEntityEntityType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectObjectEntityEntityType + && this.string.equals(((DetectObjectEntityEntityType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case FACE: + return visitor.visitFace(); + case SIGNATURE: + return visitor.visitSignature(); + case LICENSE_PLATE: + return visitor.visitLicensePlate(); + case ALL: + return visitor.visitAll(); + case NONE: + return visitor.visitNone(); + case LOGO: + return visitor.visitLogo(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectObjectEntityEntityType valueOf(String value) { + switch (value) { + case "FACE": + return FACE; + case "SIGNATURE": + return SIGNATURE; + case "LICENSE_PLATE": + return LICENSE_PLATE; + case "ALL": + return ALL; + case "NONE": + return NONE; + case "LOGO": + return LOGO; + default: + return new DetectObjectEntityEntityType(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + FACE, + + LICENSE_PLATE, + + LOGO, + + SIGNATURE, + + ALL, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitFace(); + + T visitLicensePlate(); + + T visitLogo(); + + T visitSignature(); + + T visitAll(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectReturnEntities.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectReturnEntities.java new file mode 100644 index 00000000..f5435ec2 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectReturnEntities.java @@ -0,0 +1,94 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectReturnEntities { + public static final DetectReturnEntities ALL = new DetectReturnEntities(Value.ALL, "ALL"); + + public static final DetectReturnEntities NONE = new DetectReturnEntities(Value.NONE, "NONE"); + + public static final DetectReturnEntities EXCLUDE_SENSITIVE_DATA = + new DetectReturnEntities(Value.EXCLUDE_SENSITIVE_DATA, "EXCLUDE_SENSITIVE_DATA"); + + private final Value value; + + private final String string; + + DetectReturnEntities(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectReturnEntities && this.string.equals(((DetectReturnEntities) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ALL: + return visitor.visitAll(); + case NONE: + return visitor.visitNone(); + case EXCLUDE_SENSITIVE_DATA: + return visitor.visitExcludeSensitiveData(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectReturnEntities valueOf(String value) { + switch (value) { + case "ALL": + return ALL; + case "NONE": + return NONE; + case "EXCLUDE_SENSITIVE_DATA": + return EXCLUDE_SENSITIVE_DATA; + default: + return new DetectReturnEntities(Value.UNKNOWN, value); + } + } + + public enum Value { + EXCLUDE_SENSITIVE_DATA, + + ALL, + + NONE, + + UNKNOWN + } + + public interface Visitor { + T visitExcludeSensitiveData(); + + T visitAll(); + + T visitNone(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2.java new file mode 100644 index 00000000..372e164d --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2.java @@ -0,0 +1,228 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectRunsResponseV2.Builder.class) +public final class DetectRunsResponseV2 { + private final Optional status; + + private final Optional outputType; + + private final Optional> output; + + private final Optional message; + + private final Optional metrics; + + private final Map additionalProperties; + + private DetectRunsResponseV2( + Optional status, + Optional outputType, + Optional> output, + Optional message, + Optional metrics, + Map additionalProperties) { + this.status = status; + this.outputType = outputType; + this.output = output; + this.message = message; + this.metrics = metrics; + this.additionalProperties = additionalProperties; + } + + /** + * @return Status of the detect run. + */ + @JsonProperty("status") + public Optional getStatus() { + return status; + } + + /** + * @return Data source of the output file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file. + */ + @JsonProperty("outputType") + public Optional getOutputType() { + return outputType; + } + + /** + * @return Details of output files. + */ + @JsonProperty("output") + public Optional> getOutput() { + return output; + } + + /** + * @return Status details about the Detect run. + */ + @JsonProperty("message") + public Optional getMessage() { + return message; + } + + @JsonProperty("metrics") + public Optional getMetrics() { + return metrics; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectRunsResponseV2 && equalTo((DetectRunsResponseV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectRunsResponseV2 other) { + return status.equals(other.status) + && outputType.equals(other.outputType) + && output.equals(other.output) + && message.equals(other.message) + && metrics.equals(other.metrics); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.status, this.outputType, this.output, this.message, this.metrics); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional status = Optional.empty(); + + private Optional outputType = Optional.empty(); + + private Optional> output = Optional.empty(); + + private Optional message = Optional.empty(); + + private Optional metrics = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetectRunsResponseV2 other) { + status(other.getStatus()); + outputType(other.getOutputType()); + output(other.getOutput()); + message(other.getMessage()); + metrics(other.getMetrics()); + return this; + } + + /** + *

Status of the detect run.

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

Data source of the output file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file.

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

Details of output files.

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

Status details about the Detect run.

+ */ + @JsonSetter(value = "message", nulls = Nulls.SKIP) + public Builder message(Optional message) { + this.message = message; + return this; + } + + public Builder message(String message) { + this.message = Optional.ofNullable(message); + return this; + } + + @JsonSetter(value = "metrics", nulls = Nulls.SKIP) + public Builder metrics(Optional metrics) { + this.metrics = metrics; + return this; + } + + public Builder metrics(Metrics metrics) { + this.metrics = Optional.ofNullable(metrics); + return this; + } + + public DetectRunsResponseV2 build() { + return new DetectRunsResponseV2(status, outputType, output, message, metrics, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2OutputType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2OutputType.java new file mode 100644 index 00000000..cb995d80 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2OutputType.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectRunsResponseV2OutputType { + public static final DetectRunsResponseV2OutputType BASE64 = + new DetectRunsResponseV2OutputType(Value.BASE64, "BASE64"); + + public static final DetectRunsResponseV2OutputType SKYFLOW_ID = + new DetectRunsResponseV2OutputType(Value.SKYFLOW_ID, "SKYFLOW_ID"); + + public static final DetectRunsResponseV2OutputType PRESIGNED_URL = + new DetectRunsResponseV2OutputType(Value.PRESIGNED_URL, "PRESIGNED_URL"); + + private final Value value; + + private final String string; + + DetectRunsResponseV2OutputType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectRunsResponseV2OutputType + && this.string.equals(((DetectRunsResponseV2OutputType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BASE64: + return visitor.visitBase64(); + case SKYFLOW_ID: + return visitor.visitSkyflowId(); + case PRESIGNED_URL: + return visitor.visitPresignedUrl(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectRunsResponseV2OutputType valueOf(String value) { + switch (value) { + case "BASE64": + return BASE64; + case "SKYFLOW_ID": + return SKYFLOW_ID; + case "PRESIGNED_URL": + return PRESIGNED_URL; + default: + return new DetectRunsResponseV2OutputType(Value.UNKNOWN, value); + } + } + + public enum Value { + BASE64, + + SKYFLOW_ID, + + PRESIGNED_URL, + + UNKNOWN + } + + public interface Visitor { + T visitBase64(); + + T visitSkyflowId(); + + T visitPresignedUrl(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2Status.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2Status.java new file mode 100644 index 00000000..c4549699 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DetectRunsResponseV2Status.java @@ -0,0 +1,115 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetectRunsResponseV2Status { + public static final DetectRunsResponseV2Status IN_PROGRESS = + new DetectRunsResponseV2Status(Value.IN_PROGRESS, "IN_PROGRESS"); + + public static final DetectRunsResponseV2Status QUEUED = new DetectRunsResponseV2Status(Value.QUEUED, "QUEUED"); + + public static final DetectRunsResponseV2Status SUCCESS = new DetectRunsResponseV2Status(Value.SUCCESS, "SUCCESS"); + + public static final DetectRunsResponseV2Status UNKNOWN = new DetectRunsResponseV2Status(Value.UNKNOWN, "UNKNOWN"); + + public static final DetectRunsResponseV2Status FAILED = new DetectRunsResponseV2Status(Value.FAILED, "FAILED"); + + private final Value value; + + private final String string; + + DetectRunsResponseV2Status(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetectRunsResponseV2Status + && this.string.equals(((DetectRunsResponseV2Status) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case IN_PROGRESS: + return visitor.visitInProgress(); + case QUEUED: + return visitor.visitQueued(); + case SUCCESS: + return visitor.visitSuccess(); + case UNKNOWN: + return visitor.visitUnknown(); + case FAILED: + return visitor.visitFailed(); + case _UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetectRunsResponseV2Status valueOf(String value) { + switch (value) { + case "IN_PROGRESS": + return IN_PROGRESS; + case "QUEUED": + return QUEUED; + case "SUCCESS": + return SUCCESS; + case "UNKNOWN": + return UNKNOWN; + case "FAILED": + return FAILED; + default: + return new DetectRunsResponseV2Status(Value._UNKNOWN, value); + } + } + + public enum Value { + UNKNOWN, + + FAILED, + + SUCCESS, + + IN_PROGRESS, + + QUEUED, + + _UNKNOWN + } + + public interface Visitor { + T visitUnknown(); + + T visitFailed(); + + T visitSuccess(); + + T visitInProgress(); + + T visitQueued(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2.java new file mode 100644 index 00000000..4e080422 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2.java @@ -0,0 +1,105 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DocumentV2.Builder.class) +public final class DocumentV2 { + private final Optional pdf; + + private final Map additionalProperties; + + private DocumentV2(Optional pdf, Map additionalProperties) { + this.pdf = pdf; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("pdf") + public Optional getPdf() { + return pdf; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DocumentV2 && equalTo((DocumentV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DocumentV2 other) { + return pdf.equals(other.pdf); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.pdf); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional pdf = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DocumentV2 other) { + pdf(other.getPdf()); + return this; + } + + @JsonSetter(value = "pdf", nulls = Nulls.SKIP) + public Builder pdf(Optional pdf) { + this.pdf = pdf; + return this; + } + + public Builder pdf(DocumentV2Pdf pdf) { + this.pdf = Optional.ofNullable(pdf); + return this; + } + + public DocumentV2 build() { + return new DocumentV2(pdf, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2Pdf.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2Pdf.java new file mode 100644 index 00000000..4aae1940 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2Pdf.java @@ -0,0 +1,173 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DocumentV2Pdf.Builder.class) +public final class DocumentV2Pdf { + private final Optional processingMode; + + private final Optional density; + + private final Optional maxResolution; + + private final Map additionalProperties; + + private DocumentV2Pdf( + Optional processingMode, + Optional density, + Optional maxResolution, + Map additionalProperties) { + this.processingMode = processingMode; + this.density = density; + this.maxResolution = maxResolution; + this.additionalProperties = additionalProperties; + } + + /** + * @return Processing mode for the PDF file. TEXT_LAYER: processes the PDF's native text layer and replaces detected entities with entity tokens (for example, [NAME_1]). Fast and accurate for PDFs with selectable text. OCR: processes the PDF as an image using optical character recognition and covers detected content with a gray box. Use for scanned or image-based PDFs. Because OCR rasterizes each page, the output PDF file size can be significantly larger than the input. + */ + @JsonProperty("processingMode") + public Optional getProcessingMode() { + return processingMode; + } + + /** + * @return Pixel density at which to process the PDF file. Applies only when processingMode is OCR. + */ + @JsonProperty("density") + public Optional getDensity() { + return density; + } + + /** + * @return Max resolution at which to process the PDF file. Applies only when processingMode is OCR. + */ + @JsonProperty("maxResolution") + public Optional getMaxResolution() { + return maxResolution; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DocumentV2Pdf && equalTo((DocumentV2Pdf) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DocumentV2Pdf other) { + return processingMode.equals(other.processingMode) + && density.equals(other.density) + && maxResolution.equals(other.maxResolution); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.processingMode, this.density, this.maxResolution); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional processingMode = Optional.empty(); + + private Optional density = Optional.empty(); + + private Optional maxResolution = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DocumentV2Pdf other) { + processingMode(other.getProcessingMode()); + density(other.getDensity()); + maxResolution(other.getMaxResolution()); + return this; + } + + /** + *

Processing mode for the PDF file. TEXT_LAYER: processes the PDF's native text layer and replaces detected entities with entity tokens (for example, [NAME_1]). Fast and accurate for PDFs with selectable text. OCR: processes the PDF as an image using optical character recognition and covers detected content with a gray box. Use for scanned or image-based PDFs. Because OCR rasterizes each page, the output PDF file size can be significantly larger than the input.

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

Pixel density at which to process the PDF file. Applies only when processingMode is OCR.

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

Max resolution at which to process the PDF file. Applies only when processingMode is OCR.

+ */ + @JsonSetter(value = "maxResolution", nulls = Nulls.SKIP) + public Builder maxResolution(Optional maxResolution) { + this.maxResolution = maxResolution; + return this; + } + + public Builder maxResolution(Integer maxResolution) { + this.maxResolution = Optional.ofNullable(maxResolution); + return this; + } + + public DocumentV2Pdf build() { + return new DocumentV2Pdf(processingMode, density, maxResolution, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2PdfProcessingMode.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2PdfProcessingMode.java new file mode 100644 index 00000000..2ada581f --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/DocumentV2PdfProcessingMode.java @@ -0,0 +1,95 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DocumentV2PdfProcessingMode { + public static final DocumentV2PdfProcessingMode OCR = new DocumentV2PdfProcessingMode(Value.OCR, "OCR"); + + public static final DocumentV2PdfProcessingMode NONE = new DocumentV2PdfProcessingMode(Value.NONE, "NONE"); + + public static final DocumentV2PdfProcessingMode TEXT_LAYER = + new DocumentV2PdfProcessingMode(Value.TEXT_LAYER, "TEXT_LAYER"); + + private final Value value; + + private final String string; + + DocumentV2PdfProcessingMode(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DocumentV2PdfProcessingMode + && this.string.equals(((DocumentV2PdfProcessingMode) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case OCR: + return visitor.visitOcr(); + case NONE: + return visitor.visitNone(); + case TEXT_LAYER: + return visitor.visitTextLayer(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DocumentV2PdfProcessingMode valueOf(String value) { + switch (value) { + case "OCR": + return OCR; + case "NONE": + return NONE; + case "TEXT_LAYER": + return TEXT_LAYER; + default: + return new DocumentV2PdfProcessingMode(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + OCR, + + TEXT_LAYER, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitOcr(); + + T visitTextLayer(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/EntityTransformation.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/EntityTransformation.java new file mode 100644 index 00000000..870b3e13 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/EntityTransformation.java @@ -0,0 +1,106 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = EntityTransformation.Builder.class) +public final class EntityTransformation { + private final Optional shiftDates; + + private final Map additionalProperties; + + private EntityTransformation( + Optional shiftDates, Map additionalProperties) { + this.shiftDates = shiftDates; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("shiftDates") + public Optional getShiftDates() { + return shiftDates; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof EntityTransformation && equalTo((EntityTransformation) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(EntityTransformation other) { + return shiftDates.equals(other.shiftDates); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.shiftDates); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional shiftDates = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(EntityTransformation other) { + shiftDates(other.getShiftDates()); + return this; + } + + @JsonSetter(value = "shiftDates", nulls = Nulls.SKIP) + public Builder shiftDates(Optional shiftDates) { + this.shiftDates = shiftDates; + return this; + } + + public Builder shiftDates(TransformationShiftDates shiftDates) { + this.shiftDates = Optional.ofNullable(shiftDates); + return this; + } + + public EntityTransformation build() { + return new EntityTransformation(shiftDates, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/ErrorResponse.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/ErrorResponse.java new file mode 100644 index 00000000..4e29036e --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/ErrorResponse.java @@ -0,0 +1,118 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ErrorResponse.Builder.class) +public final class ErrorResponse { + private final ErrorResponseError error; + + private final Map additionalProperties; + + private ErrorResponse(ErrorResponseError error, Map additionalProperties) { + this.error = error; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("error") + public ErrorResponseError getError() { + return error; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ErrorResponse && equalTo((ErrorResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ErrorResponse other) { + return error.equals(other.error); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.error); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ErrorStage builder() { + return new Builder(); + } + + public interface ErrorStage { + _FinalStage error(@NotNull ErrorResponseError error); + + Builder from(ErrorResponse other); + } + + public interface _FinalStage { + ErrorResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ErrorStage, _FinalStage { + private ErrorResponseError error; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ErrorResponse other) { + error(other.getError()); + return this; + } + + @java.lang.Override + @JsonSetter("error") + public _FinalStage error(@NotNull ErrorResponseError error) { + this.error = Objects.requireNonNull(error, "error must not be null"); + return this; + } + + @java.lang.Override + public ErrorResponse build() { + return new ErrorResponse(error, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/ErrorResponseError.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/ErrorResponseError.java new file mode 100644 index 00000000..5c43d6a6 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/ErrorResponseError.java @@ -0,0 +1,236 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ErrorResponseError.Builder.class) +public final class ErrorResponseError { + private final int grpcCode; + + private final int httpCode; + + private final String httpStatus; + + private final String message; + + private final Optional>> details; + + private final Map additionalProperties; + + private ErrorResponseError( + int grpcCode, + int httpCode, + String httpStatus, + String message, + Optional>> details, + Map additionalProperties) { + this.grpcCode = grpcCode; + this.httpCode = httpCode; + this.httpStatus = httpStatus; + this.message = message; + this.details = details; + this.additionalProperties = additionalProperties; + } + + /** + * @return gRPC status codes. See https://grpc.io/docs/guides/status-codes. + */ + @JsonProperty("grpc_code") + public int getGrpcCode() { + return grpcCode; + } + + @JsonProperty("http_code") + public int getHttpCode() { + return httpCode; + } + + @JsonProperty("http_status") + public String getHttpStatus() { + return httpStatus; + } + + @JsonProperty("message") + public String getMessage() { + return message; + } + + @JsonProperty("details") + public Optional>> getDetails() { + return details; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ErrorResponseError && equalTo((ErrorResponseError) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ErrorResponseError other) { + return grpcCode == other.grpcCode + && httpCode == other.httpCode + && httpStatus.equals(other.httpStatus) + && message.equals(other.message) + && details.equals(other.details); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.grpcCode, this.httpCode, this.httpStatus, this.message, this.details); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static GrpcCodeStage builder() { + return new Builder(); + } + + public interface GrpcCodeStage { + /** + *

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

+ */ + HttpCodeStage grpcCode(int grpcCode); + + Builder from(ErrorResponseError other); + } + + public interface HttpCodeStage { + HttpStatusStage httpCode(int httpCode); + } + + public interface HttpStatusStage { + MessageStage httpStatus(@NotNull String httpStatus); + } + + public interface MessageStage { + _FinalStage message(@NotNull String message); + } + + public interface _FinalStage { + ErrorResponseError build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + _FinalStage details(Optional>> details); + + _FinalStage details(List> details); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder + implements GrpcCodeStage, HttpCodeStage, HttpStatusStage, MessageStage, _FinalStage { + private int grpcCode; + + private int httpCode; + + private String httpStatus; + + private String message; + + private Optional>> details = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ErrorResponseError other) { + grpcCode(other.getGrpcCode()); + httpCode(other.getHttpCode()); + httpStatus(other.getHttpStatus()); + message(other.getMessage()); + details(other.getDetails()); + return this; + } + + /** + *

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

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("grpc_code") + public HttpCodeStage grpcCode(int grpcCode) { + this.grpcCode = grpcCode; + return this; + } + + @java.lang.Override + @JsonSetter("http_code") + public HttpStatusStage httpCode(int httpCode) { + this.httpCode = httpCode; + return this; + } + + @java.lang.Override + @JsonSetter("http_status") + public MessageStage httpStatus(@NotNull String httpStatus) { + this.httpStatus = Objects.requireNonNull(httpStatus, "httpStatus must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("message") + public _FinalStage message(@NotNull String message) { + this.message = Objects.requireNonNull(message, "message must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage details(List> details) { + this.details = Optional.ofNullable(details); + return this; + } + + @java.lang.Override + @JsonSetter(value = "details", nulls = Nulls.SKIP) + public _FinalStage details(Optional>> details) { + this.details = details; + return this; + } + + @java.lang.Override + public ErrorResponseError build() { + return new ErrorResponseError(grpcCode, httpCode, httpStatus, message, details, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/FileMapping.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/FileMapping.java new file mode 100644 index 00000000..75b023be --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/FileMapping.java @@ -0,0 +1,244 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileMapping.Builder.class) +public final class FileMapping { + private final Optional source; + + private final Optional destination; + + private final Optional outputFileNameSuffix; + + private final Optional entitiesDestination; + + private final Optional objectEntitiesDestination; + + private final Map additionalProperties; + + private FileMapping( + Optional source, + Optional destination, + Optional outputFileNameSuffix, + Optional entitiesDestination, + Optional objectEntitiesDestination, + Map additionalProperties) { + this.source = source; + this.destination = destination; + this.outputFileNameSuffix = outputFileNameSuffix; + this.entitiesDestination = entitiesDestination; + this.objectEntitiesDestination = objectEntitiesDestination; + this.additionalProperties = additionalProperties; + } + + /** + * @return Location of the source file. + */ + @JsonProperty("source") + public Optional getSource() { + return source; + } + + /** + * @return Location of the target file. + */ + @JsonProperty("destination") + public Optional getDestination() { + return destination; + } + + /** + * @return Suffix of the output file. For example, with outputFileNameSuffix = "_deidentified", "invoice.pdf" becomes "invoice_deidentified.pdf". + */ + @JsonProperty("outputFileNameSuffix") + public Optional getOutputFileNameSuffix() { + return outputFileNameSuffix; + } + + /** + * @return Location of the entities output, as "table.column". For example, "documents.entities_json". Must be in the same table as source. If unset, the entities output is not stored in the vault. + */ + @JsonProperty("entitiesDestination") + public Optional getEntitiesDestination() { + return entitiesDestination; + } + + /** + * @return Location of the object entities output, as "table.column". For example, "documents.object_entities_json". Must be in the same table as source. If unset, the object entities output is not stored in the vault. + */ + @JsonProperty("objectEntitiesDestination") + public Optional getObjectEntitiesDestination() { + return objectEntitiesDestination; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileMapping && equalTo((FileMapping) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileMapping other) { + return source.equals(other.source) + && destination.equals(other.destination) + && outputFileNameSuffix.equals(other.outputFileNameSuffix) + && entitiesDestination.equals(other.entitiesDestination) + && objectEntitiesDestination.equals(other.objectEntitiesDestination); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.source, + this.destination, + this.outputFileNameSuffix, + this.entitiesDestination, + this.objectEntitiesDestination); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional source = Optional.empty(); + + private Optional destination = Optional.empty(); + + private Optional outputFileNameSuffix = Optional.empty(); + + private Optional entitiesDestination = Optional.empty(); + + private Optional objectEntitiesDestination = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(FileMapping other) { + source(other.getSource()); + destination(other.getDestination()); + outputFileNameSuffix(other.getOutputFileNameSuffix()); + entitiesDestination(other.getEntitiesDestination()); + objectEntitiesDestination(other.getObjectEntitiesDestination()); + return this; + } + + /** + *

Location of the source file.

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

Location of the target file.

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

Suffix of the output file. For example, with outputFileNameSuffix = "_deidentified", "invoice.pdf" becomes "invoice_deidentified.pdf".

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

Location of the entities output, as "table.column". For example, "documents.entities_json". Must be in the same table as source. If unset, the entities output is not stored in the vault.

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

Location of the object entities output, as "table.column". For example, "documents.object_entities_json". Must be in the same table as source. If unset, the object entities output is not stored in the vault.

+ */ + @JsonSetter(value = "objectEntitiesDestination", nulls = Nulls.SKIP) + public Builder objectEntitiesDestination(Optional objectEntitiesDestination) { + this.objectEntitiesDestination = objectEntitiesDestination; + return this; + } + + public Builder objectEntitiesDestination(String objectEntitiesDestination) { + this.objectEntitiesDestination = Optional.ofNullable(objectEntitiesDestination); + return this; + } + + public FileMapping build() { + return new FileMapping( + source, + destination, + outputFileNameSuffix, + entitiesDestination, + objectEntitiesDestination, + additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutput.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutput.java similarity index 57% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutput.java rename to common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutput.java index dc244be8..69f6cdf8 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutput.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutput.java @@ -1,32 +1,37 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - +import com.skyflow.generated.detect.rest.core.ObjectMappers; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifiedFileOutput.Builder.class) -public final class DeidentifiedFileOutput { +@JsonDeserialize(builder = FileOutput.Builder.class) +public final class FileOutput { private final Optional processedFile; - private final Optional processedFileType; + private final Optional processedFileType; - private final Optional processedFileExtension; + private final Optional processedFileExtension; private final Map additionalProperties; - private DeidentifiedFileOutput( + private FileOutput( Optional processedFile, - Optional processedFileType, - Optional processedFileExtension, + Optional processedFileType, + Optional processedFileExtension, Map additionalProperties) { this.processedFile = processedFile; this.processedFileType = processedFileType; @@ -35,7 +40,7 @@ private DeidentifiedFileOutput( } /** - * @return File content in Base64 format. + * @return Value of the processed file. */ @JsonProperty("processedFile") public Optional getProcessedFile() { @@ -46,22 +51,22 @@ public Optional getProcessedFile() { * @return Type of the processed file. */ @JsonProperty("processedFileType") - public Optional getProcessedFileType() { + public Optional getProcessedFileType() { return processedFileType; } /** - * @return Extension of the processed file. + * @return Processed file extension. */ @JsonProperty("processedFileExtension") - public Optional getProcessedFileExtension() { + public Optional getProcessedFileExtension() { return processedFileExtension; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof DeidentifiedFileOutput && equalTo((DeidentifiedFileOutput) other); + return other instanceof FileOutput && equalTo((FileOutput) other); } @JsonAnyGetter @@ -69,18 +74,18 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(DeidentifiedFileOutput other) { + private boolean equalTo(FileOutput other) { return processedFile.equals(other.processedFile) && processedFileType.equals(other.processedFileType) && processedFileExtension.equals(other.processedFileExtension); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.processedFile, this.processedFileType, this.processedFileExtension); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -93,16 +98,16 @@ public static Builder builder() { public static final class Builder { private Optional processedFile = Optional.empty(); - private Optional processedFileType = Optional.empty(); + private Optional processedFileType = Optional.empty(); - private Optional processedFileExtension = Optional.empty(); + private Optional processedFileExtension = Optional.empty(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} - public Builder from(DeidentifiedFileOutput other) { + public Builder from(FileOutput other) { processedFile(other.getProcessedFile()); processedFileType(other.getProcessedFileType()); processedFileExtension(other.getProcessedFileExtension()); @@ -110,7 +115,7 @@ public Builder from(DeidentifiedFileOutput other) { } /** - *

File content in Base64 format.

+ *

Value of the processed file.

*/ @JsonSetter(value = "processedFile", nulls = Nulls.SKIP) public Builder processedFile(Optional processedFile) { @@ -127,34 +132,42 @@ public Builder processedFile(String processedFile) { *

Type of the processed file.

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

Extension of the processed file.

+ *

Processed file extension.

*/ @JsonSetter(value = "processedFileExtension", nulls = Nulls.SKIP) - public Builder processedFileExtension( - Optional processedFileExtension) { + public Builder processedFileExtension(Optional processedFileExtension) { this.processedFileExtension = processedFileExtension; return this; } - public Builder processedFileExtension(DeidentifiedFileOutputProcessedFileExtension processedFileExtension) { + public Builder processedFileExtension(FileOutputProcessedFileExtension processedFileExtension) { this.processedFileExtension = Optional.ofNullable(processedFileExtension); return this; } - public DeidentifiedFileOutput build() { - return new DeidentifiedFileOutput( - processedFile, processedFileType, processedFileExtension, additionalProperties); + public FileOutput build() { + return new FileOutput(processedFile, processedFileType, processedFileExtension, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutputProcessedFileExtension.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutputProcessedFileExtension.java new file mode 100644 index 00000000..5eb8fd6f --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutputProcessedFileExtension.java @@ -0,0 +1,301 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class FileOutputProcessedFileExtension { + public static final FileOutputProcessedFileExtension BMP = new FileOutputProcessedFileExtension(Value.BMP, "bmp"); + + public static final FileOutputProcessedFileExtension PPTX = + new FileOutputProcessedFileExtension(Value.PPTX, "pptx"); + + public static final FileOutputProcessedFileExtension WAV = new FileOutputProcessedFileExtension(Value.WAV, "wav"); + + public static final FileOutputProcessedFileExtension DOC = new FileOutputProcessedFileExtension(Value.DOC, "doc"); + + public static final FileOutputProcessedFileExtension XML = new FileOutputProcessedFileExtension(Value.XML, "xml"); + + public static final FileOutputProcessedFileExtension ZIP = new FileOutputProcessedFileExtension(Value.ZIP, "zip"); + + public static final FileOutputProcessedFileExtension MP3 = new FileOutputProcessedFileExtension(Value.MP3, "mp3"); + + public static final FileOutputProcessedFileExtension PPT = new FileOutputProcessedFileExtension(Value.PPT, "ppt"); + + public static final FileOutputProcessedFileExtension JPEG = + new FileOutputProcessedFileExtension(Value.JPEG, "jpeg"); + + public static final FileOutputProcessedFileExtension TIFF = + new FileOutputProcessedFileExtension(Value.TIFF, "tiff"); + + public static final FileOutputProcessedFileExtension PDF = new FileOutputProcessedFileExtension(Value.PDF, "pdf"); + + public static final FileOutputProcessedFileExtension DOCX = + new FileOutputProcessedFileExtension(Value.DOCX, "docx"); + + public static final FileOutputProcessedFileExtension PNG = new FileOutputProcessedFileExtension(Value.PNG, "png"); + + public static final FileOutputProcessedFileExtension JSONL = + new FileOutputProcessedFileExtension(Value.JSONL, "jsonl"); + + public static final FileOutputProcessedFileExtension CSV = new FileOutputProcessedFileExtension(Value.CSV, "csv"); + + public static final FileOutputProcessedFileExtension JPG = new FileOutputProcessedFileExtension(Value.JPG, "jpg"); + + public static final FileOutputProcessedFileExtension DCM = new FileOutputProcessedFileExtension(Value.DCM, "dcm"); + + public static final FileOutputProcessedFileExtension JSON = + new FileOutputProcessedFileExtension(Value.JSON, "json"); + + public static final FileOutputProcessedFileExtension GIF = new FileOutputProcessedFileExtension(Value.GIF, "gif"); + + public static final FileOutputProcessedFileExtension TXT = new FileOutputProcessedFileExtension(Value.TXT, "txt"); + + public static final FileOutputProcessedFileExtension XLS = new FileOutputProcessedFileExtension(Value.XLS, "xls"); + + public static final FileOutputProcessedFileExtension XLSX = + new FileOutputProcessedFileExtension(Value.XLSX, "xlsx"); + + public static final FileOutputProcessedFileExtension TIF = new FileOutputProcessedFileExtension(Value.TIF, "tif"); + + private final Value value; + + private final String string; + + FileOutputProcessedFileExtension(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof FileOutputProcessedFileExtension + && this.string.equals(((FileOutputProcessedFileExtension) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BMP: + return visitor.visitBmp(); + case PPTX: + return visitor.visitPptx(); + case WAV: + return visitor.visitWav(); + case DOC: + return visitor.visitDoc(); + case XML: + return visitor.visitXml(); + case ZIP: + return visitor.visitZip(); + case MP3: + return visitor.visitMp3(); + case PPT: + return visitor.visitPpt(); + case JPEG: + return visitor.visitJpeg(); + case TIFF: + return visitor.visitTiff(); + case PDF: + return visitor.visitPdf(); + case DOCX: + return visitor.visitDocx(); + case PNG: + return visitor.visitPng(); + case JSONL: + return visitor.visitJsonl(); + case CSV: + return visitor.visitCsv(); + case JPG: + return visitor.visitJpg(); + case DCM: + return visitor.visitDcm(); + case JSON: + return visitor.visitJson(); + case GIF: + return visitor.visitGif(); + case TXT: + return visitor.visitTxt(); + case XLS: + return visitor.visitXls(); + case XLSX: + return visitor.visitXlsx(); + case TIF: + return visitor.visitTif(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static FileOutputProcessedFileExtension valueOf(String value) { + switch (value) { + case "bmp": + return BMP; + case "pptx": + return PPTX; + case "wav": + return WAV; + case "doc": + return DOC; + case "xml": + return XML; + case "zip": + return ZIP; + case "mp3": + return MP3; + case "ppt": + return PPT; + case "jpeg": + return JPEG; + case "tiff": + return TIFF; + case "pdf": + return PDF; + case "docx": + return DOCX; + case "png": + return PNG; + case "jsonl": + return JSONL; + case "csv": + return CSV; + case "jpg": + return JPG; + case "dcm": + return DCM; + case "json": + return JSON; + case "gif": + return GIF; + case "txt": + return TXT; + case "xls": + return XLS; + case "xlsx": + return XLSX; + case "tif": + return TIF; + default: + return new FileOutputProcessedFileExtension(Value.UNKNOWN, value); + } + } + + public enum Value { + MP3, + + WAV, + + PDF, + + TXT, + + CSV, + + JSON, + + JPG, + + JPEG, + + TIF, + + TIFF, + + PNG, + + BMP, + + XLS, + + XLSX, + + DOC, + + DOCX, + + PPT, + + PPTX, + + XML, + + DCM, + + JSONL, + + ZIP, + + GIF, + + UNKNOWN + } + + public interface Visitor { + T visitMp3(); + + T visitWav(); + + T visitPdf(); + + T visitTxt(); + + T visitCsv(); + + T visitJson(); + + T visitJpg(); + + T visitJpeg(); + + T visitTif(); + + T visitTiff(); + + T visitPng(); + + T visitBmp(); + + T visitXls(); + + T visitXlsx(); + + T visitDoc(); + + T visitDocx(); + + T visitPpt(); + + T visitPptx(); + + T visitXml(); + + T visitDcm(); + + T visitJsonl(); + + T visitZip(); + + T visitGif(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutputProcessedFileType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutputProcessedFileType.java new file mode 100644 index 00000000..faeb8849 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/FileOutputProcessedFileType.java @@ -0,0 +1,64 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class FileOutputProcessedFileType { + private final Value value; + + private final String string; + + FileOutputProcessedFileType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof FileOutputProcessedFileType + && this.string.equals(((FileOutputProcessedFileType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static FileOutputProcessedFileType valueOf(String value) { + switch (value) { + default: + return new FileOutputProcessedFileType(Value.UNKNOWN, value); + } + } + + public enum Value { + UNKNOWN + } + + public interface Visitor { + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/ImageV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/ImageV2.java new file mode 100644 index 00000000..ebcc89de --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/ImageV2.java @@ -0,0 +1,173 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ImageV2.Builder.class) +public final class ImageV2 { + private final Optional outputProcessedImage; + + private final Optional outputOcrText; + + private final Optional maskingMethod; + + private final Map additionalProperties; + + private ImageV2( + Optional outputProcessedImage, + Optional outputOcrText, + Optional maskingMethod, + Map additionalProperties) { + this.outputProcessedImage = outputProcessedImage; + this.outputOcrText = outputOcrText; + this.maskingMethod = maskingMethod; + this.additionalProperties = additionalProperties; + } + + /** + * @return If true, includes processed image in the output. + */ + @JsonProperty("outputProcessedImage") + public Optional getOutputProcessedImage() { + return outputProcessedImage; + } + + /** + * @return If true, includes text detected by OCR in the response. + */ + @JsonProperty("outputOcrText") + public Optional getOutputOcrText() { + return outputOcrText; + } + + /** + * @return Method used to mask detected entities in the image. BLUR: blurs each detected entity so the sensitive content is unreadable while the rest of the image is preserved. BLACKBOX: covers each detected entity with a solid black box. + */ + @JsonProperty("maskingMethod") + public Optional getMaskingMethod() { + return maskingMethod; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ImageV2 && equalTo((ImageV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ImageV2 other) { + return outputProcessedImage.equals(other.outputProcessedImage) + && outputOcrText.equals(other.outputOcrText) + && maskingMethod.equals(other.maskingMethod); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.outputProcessedImage, this.outputOcrText, this.maskingMethod); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional outputProcessedImage = Optional.empty(); + + private Optional outputOcrText = Optional.empty(); + + private Optional maskingMethod = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ImageV2 other) { + outputProcessedImage(other.getOutputProcessedImage()); + outputOcrText(other.getOutputOcrText()); + maskingMethod(other.getMaskingMethod()); + return this; + } + + /** + *

If true, includes processed image in the output.

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

If true, includes text detected by OCR in the response.

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

Method used to mask detected entities in the image. BLUR: blurs each detected entity so the sensitive content is unreadable while the rest of the image is preserved. BLACKBOX: covers each detected entity with a solid black box.

+ */ + @JsonSetter(value = "maskingMethod", nulls = Nulls.SKIP) + public Builder maskingMethod(Optional maskingMethod) { + this.maskingMethod = maskingMethod; + return this; + } + + public Builder maskingMethod(ImageV2MaskingMethod maskingMethod) { + this.maskingMethod = Optional.ofNullable(maskingMethod); + return this; + } + + public ImageV2 build() { + return new ImageV2(outputProcessedImage, outputOcrText, maskingMethod, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/ImageV2MaskingMethod.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/ImageV2MaskingMethod.java new file mode 100644 index 00000000..41f59512 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/ImageV2MaskingMethod.java @@ -0,0 +1,93 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class ImageV2MaskingMethod { + public static final ImageV2MaskingMethod BLUR = new ImageV2MaskingMethod(Value.BLUR, "BLUR"); + + public static final ImageV2MaskingMethod NONE = new ImageV2MaskingMethod(Value.NONE, "NONE"); + + public static final ImageV2MaskingMethod BLACKBOX = new ImageV2MaskingMethod(Value.BLACKBOX, "BLACKBOX"); + + private final Value value; + + private final String string; + + ImageV2MaskingMethod(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ImageV2MaskingMethod && this.string.equals(((ImageV2MaskingMethod) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BLUR: + return visitor.visitBlur(); + case NONE: + return visitor.visitNone(); + case BLACKBOX: + return visitor.visitBlackbox(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ImageV2MaskingMethod valueOf(String value) { + switch (value) { + case "BLUR": + return BLUR; + case "NONE": + return NONE; + case "BLACKBOX": + return BLACKBOX; + default: + return new ImageV2MaskingMethod(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + BLUR, + + BLACKBOX, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitBlur(); + + T visitBlackbox(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/Media.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/Media.java new file mode 100644 index 00000000..7bba13bb --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/Media.java @@ -0,0 +1,153 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = Media.Builder.class) +public final class Media { + private final Optional audio; + + private final Optional document; + + private final Optional image; + + private final Map additionalProperties; + + private Media( + Optional audio, + Optional document, + Optional image, + Map additionalProperties) { + this.audio = audio; + this.document = document; + this.image = image; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("audio") + public Optional getAudio() { + return audio; + } + + @JsonProperty("document") + public Optional getDocument() { + return document; + } + + @JsonProperty("image") + public Optional getImage() { + return image; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof Media && equalTo((Media) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(Media other) { + return audio.equals(other.audio) && document.equals(other.document) && image.equals(other.image); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.audio, this.document, this.image); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional audio = Optional.empty(); + + private Optional document = Optional.empty(); + + private Optional image = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(Media other) { + audio(other.getAudio()); + document(other.getDocument()); + image(other.getImage()); + return this; + } + + @JsonSetter(value = "audio", nulls = Nulls.SKIP) + public Builder audio(Optional audio) { + this.audio = audio; + return this; + } + + public Builder audio(AudioV2 audio) { + this.audio = Optional.ofNullable(audio); + return this; + } + + @JsonSetter(value = "document", nulls = Nulls.SKIP) + public Builder document(Optional document) { + this.document = document; + return this; + } + + public Builder document(DocumentV2 document) { + this.document = Optional.ofNullable(document); + return this; + } + + @JsonSetter(value = "image", nulls = Nulls.SKIP) + public Builder image(Optional image) { + this.image = image; + return this; + } + + public Builder image(ImageV2 image) { + this.image = Optional.ofNullable(image); + return this; + } + + public Media build() { + return new Media(audio, document, image, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/Metrics.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/Metrics.java new file mode 100644 index 00000000..ac525333 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/Metrics.java @@ -0,0 +1,263 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = Metrics.Builder.class) +public final class Metrics { + private final Optional size; + + private final Optional wordCount; + + private final Optional characterCount; + + private final Optional slides; + + private final Optional pages; + + private final Optional duration; + + private final Map additionalProperties; + + private Metrics( + Optional size, + Optional wordCount, + Optional characterCount, + Optional slides, + Optional pages, + Optional duration, + Map additionalProperties) { + this.size = size; + this.wordCount = wordCount; + this.characterCount = characterCount; + this.slides = slides; + this.pages = pages; + this.duration = duration; + this.additionalProperties = additionalProperties; + } + + /** + * @return Size of the input text(KB). + */ + @JsonProperty("size") + public Optional getSize() { + return size; + } + + /** + * @return Total number of words processed. + */ + @JsonProperty("wordCount") + public Optional getWordCount() { + return wordCount; + } + + /** + * @return Total number of characters processed. + */ + @JsonProperty("characterCount") + public Optional getCharacterCount() { + return characterCount; + } + + /** + * @return Total number of slides processed. + */ + @JsonProperty("slides") + public Optional getSlides() { + return slides; + } + + /** + * @return Total number of pages processed. + */ + @JsonProperty("pages") + public Optional getPages() { + return pages; + } + + /** + * @return Total duration processed(seconds). + */ + @JsonProperty("duration") + public Optional getDuration() { + return duration; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof Metrics && equalTo((Metrics) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(Metrics other) { + return size.equals(other.size) + && wordCount.equals(other.wordCount) + && characterCount.equals(other.characterCount) + && slides.equals(other.slides) + && pages.equals(other.pages) + && duration.equals(other.duration); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.size, this.wordCount, this.characterCount, this.slides, this.pages, this.duration); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional size = Optional.empty(); + + private Optional wordCount = Optional.empty(); + + private Optional characterCount = Optional.empty(); + + private Optional slides = Optional.empty(); + + private Optional pages = Optional.empty(); + + private Optional duration = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(Metrics other) { + size(other.getSize()); + wordCount(other.getWordCount()); + characterCount(other.getCharacterCount()); + slides(other.getSlides()); + pages(other.getPages()); + duration(other.getDuration()); + return this; + } + + /** + *

Size of the input text(KB).

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

Total number of words processed.

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

Total number of characters processed.

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

Total number of slides processed.

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

Total number of pages processed.

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

Total duration processed(seconds).

+ */ + @JsonSetter(value = "duration", nulls = Nulls.SKIP) + public Builder duration(Optional duration) { + this.duration = duration; + return this; + } + + public Builder duration(Double duration) { + this.duration = Optional.ofNullable(duration); + return this; + } + + public Metrics build() { + return new Metrics(size, wordCount, characterCount, slides, pages, duration, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevel.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevel.java new file mode 100644 index 00000000..961c2f2f --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevel.java @@ -0,0 +1,204 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RedactionLevel.Builder.class) +public final class RedactionLevel { + private final Optional tokenGroupName; + + private final Optional entityName; + + private final Optional redactionType; + + private final Optional redactionPattern; + + private final Map additionalProperties; + + private RedactionLevel( + Optional tokenGroupName, + Optional entityName, + Optional redactionType, + Optional redactionPattern, + Map additionalProperties) { + this.tokenGroupName = tokenGroupName; + this.entityName = entityName; + this.redactionType = redactionType; + this.redactionPattern = redactionPattern; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the token group whose detokenized values should be masked (e.g., a token in personTokenGroup that detokenizes to John Doe is masked as JoXXXe). Use this for FlowVault. + */ + @JsonProperty("tokenGroupName") + public Optional getTokenGroupName() { + return tokenGroupName; + } + + /** + * @return Entity type whose detokenized values should be shown in plain text, redacted, or masked based on redactionType (e.g., a NAME entity that detokenizes to John Doe is masked as JoXXXe). Use this for SkyVault. + */ + @JsonProperty("entityName") + public Optional getEntityName() { + return entityName; + } + + /** + * @return Redaction method to apply to the detokenized value (e.g., for the value John Doe, MASKED transforms it into JoXXXe, REDACTED transforms it into *REDACTED*, and PLAIN_TEXT keeps it as John Doe). Use this for SkyVault. + */ + @JsonProperty("redactionType") + public Optional getRedactionType() { + return redactionType; + } + + /** + * @return Redaction method to apply to the detokenized value. Use the name of a redaction pattern configured in the vault (e.g., personMaskPattern transforms John Doe into JoXXXe). Use this for FlowVault. + */ + @JsonProperty("redactionPattern") + public Optional getRedactionPattern() { + return redactionPattern; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RedactionLevel && equalTo((RedactionLevel) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RedactionLevel other) { + return tokenGroupName.equals(other.tokenGroupName) + && entityName.equals(other.entityName) + && redactionType.equals(other.redactionType) + && redactionPattern.equals(other.redactionPattern); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tokenGroupName, this.entityName, this.redactionType, this.redactionPattern); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional tokenGroupName = Optional.empty(); + + private Optional entityName = Optional.empty(); + + private Optional redactionType = Optional.empty(); + + private Optional redactionPattern = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(RedactionLevel other) { + tokenGroupName(other.getTokenGroupName()); + entityName(other.getEntityName()); + redactionType(other.getRedactionType()); + redactionPattern(other.getRedactionPattern()); + return this; + } + + /** + *

Name of the token group whose detokenized values should be masked (e.g., a token in personTokenGroup that detokenizes to John Doe is masked as JoXXXe). Use this for FlowVault.

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

Entity type whose detokenized values should be shown in plain text, redacted, or masked based on redactionType (e.g., a NAME entity that detokenizes to John Doe is masked as JoXXXe). Use this for SkyVault.

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

Redaction method to apply to the detokenized value (e.g., for the value John Doe, MASKED transforms it into JoXXXe, REDACTED transforms it into *REDACTED*, and PLAIN_TEXT keeps it as John Doe). Use this for SkyVault.

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

Redaction method to apply to the detokenized value. Use the name of a redaction pattern configured in the vault (e.g., personMaskPattern transforms John Doe into JoXXXe). Use this for FlowVault.

+ */ + @JsonSetter(value = "redactionPattern", nulls = Nulls.SKIP) + public Builder redactionPattern(Optional redactionPattern) { + this.redactionPattern = redactionPattern; + return this; + } + + public Builder redactionPattern(String redactionPattern) { + this.redactionPattern = Optional.ofNullable(redactionPattern); + return this; + } + + public RedactionLevel build() { + return new RedactionLevel( + tokenGroupName, entityName, redactionType, redactionPattern, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevelEntityName.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevelEntityName.java new file mode 100644 index 00000000..a4e9acb6 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevelEntityName.java @@ -0,0 +1,812 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class RedactionLevelEntityName { + public static final RedactionLevelEntityName PHONE_NUMBER = + new RedactionLevelEntityName(Value.PHONE_NUMBER, "PHONE_NUMBER"); + + public static final RedactionLevelEntityName USERNAME = new RedactionLevelEntityName(Value.USERNAME, "USERNAME"); + + public static final RedactionLevelEntityName VEHICLE_ID = + new RedactionLevelEntityName(Value.VEHICLE_ID, "VEHICLE_ID"); + + public static final RedactionLevelEntityName RELIGION = new RedactionLevelEntityName(Value.RELIGION, "RELIGION"); + + public static final RedactionLevelEntityName ORIGIN = new RedactionLevelEntityName(Value.ORIGIN, "ORIGIN"); + + public static final RedactionLevelEntityName PASSPORT_NUMBER = + new RedactionLevelEntityName(Value.PASSPORT_NUMBER, "PASSPORT_NUMBER"); + + public static final RedactionLevelEntityName YEAR = new RedactionLevelEntityName(Value.YEAR, "YEAR"); + + public static final RedactionLevelEntityName CONDITION = new RedactionLevelEntityName(Value.CONDITION, "CONDITION"); + + public static final RedactionLevelEntityName LOCATION = new RedactionLevelEntityName(Value.LOCATION, "LOCATION"); + + public static final RedactionLevelEntityName LOCATION_CITY = + new RedactionLevelEntityName(Value.LOCATION_CITY, "LOCATION_CITY"); + + public static final RedactionLevelEntityName LOCATION_COUNTRY = + new RedactionLevelEntityName(Value.LOCATION_COUNTRY, "LOCATION_COUNTRY"); + + public static final RedactionLevelEntityName PROJECT = new RedactionLevelEntityName(Value.PROJECT, "PROJECT"); + + public static final RedactionLevelEntityName LOCATION_ZIP = + new RedactionLevelEntityName(Value.LOCATION_ZIP, "LOCATION_ZIP"); + + public static final RedactionLevelEntityName NAME_MEDICAL_PROFESSIONAL = + new RedactionLevelEntityName(Value.NAME_MEDICAL_PROFESSIONAL, "NAME_MEDICAL_PROFESSIONAL"); + + public static final RedactionLevelEntityName BANK_ACCOUNT = + new RedactionLevelEntityName(Value.BANK_ACCOUNT, "BANK_ACCOUNT"); + + public static final RedactionLevelEntityName OCCUPATION = + new RedactionLevelEntityName(Value.OCCUPATION, "OCCUPATION"); + + public static final RedactionLevelEntityName TIME = new RedactionLevelEntityName(Value.TIME, "TIME"); + + public static final RedactionLevelEntityName LOCATION_STATE = + new RedactionLevelEntityName(Value.LOCATION_STATE, "LOCATION_STATE"); + + public static final RedactionLevelEntityName EVENT = new RedactionLevelEntityName(Value.EVENT, "EVENT"); + + public static final RedactionLevelEntityName POLITICAL_AFFILIATION = + new RedactionLevelEntityName(Value.POLITICAL_AFFILIATION, "POLITICAL_AFFILIATION"); + + public static final RedactionLevelEntityName LANGUAGE = new RedactionLevelEntityName(Value.LANGUAGE, "LANGUAGE"); + + public static final RedactionLevelEntityName ZODIAC_SIGN = + new RedactionLevelEntityName(Value.ZODIAC_SIGN, "ZODIAC_SIGN"); + + public static final RedactionLevelEntityName PRODUCT = new RedactionLevelEntityName(Value.PRODUCT, "PRODUCT"); + + public static final RedactionLevelEntityName SEXUALITY = new RedactionLevelEntityName(Value.SEXUALITY, "SEXUALITY"); + + public static final RedactionLevelEntityName DURATION = new RedactionLevelEntityName(Value.DURATION, "DURATION"); + + public static final RedactionLevelEntityName PHYSICAL_ATTRIBUTE = + new RedactionLevelEntityName(Value.PHYSICAL_ATTRIBUTE, "PHYSICAL_ATTRIBUTE"); + + public static final RedactionLevelEntityName LOCATION_ADDRESS_STREET = + new RedactionLevelEntityName(Value.LOCATION_ADDRESS_STREET, "LOCATION_ADDRESS_STREET"); + + public static final RedactionLevelEntityName MEDICAL_PROCESS = + new RedactionLevelEntityName(Value.MEDICAL_PROCESS, "MEDICAL_PROCESS"); + + public static final RedactionLevelEntityName LOCATION_ADDRESS = + new RedactionLevelEntityName(Value.LOCATION_ADDRESS, "LOCATION_ADDRESS"); + + public static final RedactionLevelEntityName FILENAME = new RedactionLevelEntityName(Value.FILENAME, "FILENAME"); + + public static final RedactionLevelEntityName DOB = new RedactionLevelEntityName(Value.DOB, "DOB"); + + public static final RedactionLevelEntityName ORGANIZATION_MEDICAL_FACILITY = + new RedactionLevelEntityName(Value.ORGANIZATION_MEDICAL_FACILITY, "ORGANIZATION_MEDICAL_FACILITY"); + + public static final RedactionLevelEntityName ROUTING_NUMBER = + new RedactionLevelEntityName(Value.ROUTING_NUMBER, "ROUTING_NUMBER"); + + public static final RedactionLevelEntityName HEALTHCARE_NUMBER = + new RedactionLevelEntityName(Value.HEALTHCARE_NUMBER, "HEALTHCARE_NUMBER"); + + public static final RedactionLevelEntityName GENDER = new RedactionLevelEntityName(Value.GENDER, "GENDER"); + + public static final RedactionLevelEntityName NAME = new RedactionLevelEntityName(Value.NAME, "NAME"); + + public static final RedactionLevelEntityName DRUG = new RedactionLevelEntityName(Value.DRUG, "DRUG"); + + public static final RedactionLevelEntityName NONE = new RedactionLevelEntityName(Value.NONE, "NONE"); + + public static final RedactionLevelEntityName DATE_INTERVAL = + new RedactionLevelEntityName(Value.DATE_INTERVAL, "DATE_INTERVAL"); + + public static final RedactionLevelEntityName MARITAL_STATUS = + new RedactionLevelEntityName(Value.MARITAL_STATUS, "MARITAL_STATUS"); + + public static final RedactionLevelEntityName CORPORATE_ACTION = + new RedactionLevelEntityName(Value.CORPORATE_ACTION, "CORPORATE_ACTION"); + + public static final RedactionLevelEntityName AGE = new RedactionLevelEntityName(Value.AGE, "AGE"); + + public static final RedactionLevelEntityName CVV = new RedactionLevelEntityName(Value.CVV, "CVV"); + + public static final RedactionLevelEntityName NAME_GIVEN = + new RedactionLevelEntityName(Value.NAME_GIVEN, "NAME_GIVEN"); + + public static final RedactionLevelEntityName DATE = new RedactionLevelEntityName(Value.DATE, "DATE"); + + public static final RedactionLevelEntityName DAY = new RedactionLevelEntityName(Value.DAY, "DAY"); + + public static final RedactionLevelEntityName EFFECT = new RedactionLevelEntityName(Value.EFFECT, "EFFECT"); + + public static final RedactionLevelEntityName MEDICAL_CODE = + new RedactionLevelEntityName(Value.MEDICAL_CODE, "MEDICAL_CODE"); + + public static final RedactionLevelEntityName NUMERICAL_PII = + new RedactionLevelEntityName(Value.NUMERICAL_PII, "NUMERICAL_PII"); + + public static final RedactionLevelEntityName TREND = new RedactionLevelEntityName(Value.TREND, "TREND"); + + public static final RedactionLevelEntityName INJURY = new RedactionLevelEntityName(Value.INJURY, "INJURY"); + + public static final RedactionLevelEntityName DRIVER_LICENSE = + new RedactionLevelEntityName(Value.DRIVER_LICENSE, "DRIVER_LICENSE"); + + public static final RedactionLevelEntityName ALL = new RedactionLevelEntityName(Value.ALL, "ALL"); + + public static final RedactionLevelEntityName ORGANIZATION_ID = + new RedactionLevelEntityName(Value.ORGANIZATION_ID, "ORGANIZATION_ID"); + + public static final RedactionLevelEntityName PASSWORD = new RedactionLevelEntityName(Value.PASSWORD, "PASSWORD"); + + public static final RedactionLevelEntityName DOSE = new RedactionLevelEntityName(Value.DOSE, "DOSE"); + + public static final RedactionLevelEntityName NAME_FAMILY = + new RedactionLevelEntityName(Value.NAME_FAMILY, "NAME_FAMILY"); + + public static final RedactionLevelEntityName MONEY = new RedactionLevelEntityName(Value.MONEY, "MONEY"); + + public static final RedactionLevelEntityName URL = new RedactionLevelEntityName(Value.URL, "URL"); + + public static final RedactionLevelEntityName LOCATION_COORDINATE = + new RedactionLevelEntityName(Value.LOCATION_COORDINATE, "LOCATION_COORDINATE"); + + public static final RedactionLevelEntityName FINANCIAL_METRIC = + new RedactionLevelEntityName(Value.FINANCIAL_METRIC, "FINANCIAL_METRIC"); + + public static final RedactionLevelEntityName ORGANIZATION = + new RedactionLevelEntityName(Value.ORGANIZATION, "ORGANIZATION"); + + public static final RedactionLevelEntityName IP_ADDRESS = + new RedactionLevelEntityName(Value.IP_ADDRESS, "IP_ADDRESS"); + + public static final RedactionLevelEntityName BLOOD_TYPE = + new RedactionLevelEntityName(Value.BLOOD_TYPE, "BLOOD_TYPE"); + + public static final RedactionLevelEntityName MONTH = new RedactionLevelEntityName(Value.MONTH, "MONTH"); + + public static final RedactionLevelEntityName CREDIT_CARD = + new RedactionLevelEntityName(Value.CREDIT_CARD, "CREDIT_CARD"); + + public static final RedactionLevelEntityName ACCOUNT_NUMBER = + new RedactionLevelEntityName(Value.ACCOUNT_NUMBER, "ACCOUNT_NUMBER"); + + public static final RedactionLevelEntityName CREDIT_CARD_EXPIRATION = + new RedactionLevelEntityName(Value.CREDIT_CARD_EXPIRATION, "CREDIT_CARD_EXPIRATION"); + + public static final RedactionLevelEntityName SSN = new RedactionLevelEntityName(Value.SSN, "SSN"); + + public static final RedactionLevelEntityName EMAIL_ADDRESS = + new RedactionLevelEntityName(Value.EMAIL_ADDRESS, "EMAIL_ADDRESS"); + + public static final RedactionLevelEntityName STATISTICS = + new RedactionLevelEntityName(Value.STATISTICS, "STATISTICS"); + + private final Value value; + + private final String string; + + RedactionLevelEntityName(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof RedactionLevelEntityName + && this.string.equals(((RedactionLevelEntityName) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case PHONE_NUMBER: + return visitor.visitPhoneNumber(); + case USERNAME: + return visitor.visitUsername(); + case VEHICLE_ID: + return visitor.visitVehicleId(); + case RELIGION: + return visitor.visitReligion(); + case ORIGIN: + return visitor.visitOrigin(); + case PASSPORT_NUMBER: + return visitor.visitPassportNumber(); + case YEAR: + return visitor.visitYear(); + case CONDITION: + return visitor.visitCondition(); + case LOCATION: + return visitor.visitLocation(); + case LOCATION_CITY: + return visitor.visitLocationCity(); + case LOCATION_COUNTRY: + return visitor.visitLocationCountry(); + case PROJECT: + return visitor.visitProject(); + case LOCATION_ZIP: + return visitor.visitLocationZip(); + case NAME_MEDICAL_PROFESSIONAL: + return visitor.visitNameMedicalProfessional(); + case BANK_ACCOUNT: + return visitor.visitBankAccount(); + case OCCUPATION: + return visitor.visitOccupation(); + case TIME: + return visitor.visitTime(); + case LOCATION_STATE: + return visitor.visitLocationState(); + case EVENT: + return visitor.visitEvent(); + case POLITICAL_AFFILIATION: + return visitor.visitPoliticalAffiliation(); + case LANGUAGE: + return visitor.visitLanguage(); + case ZODIAC_SIGN: + return visitor.visitZodiacSign(); + case PRODUCT: + return visitor.visitProduct(); + case SEXUALITY: + return visitor.visitSexuality(); + case DURATION: + return visitor.visitDuration(); + case PHYSICAL_ATTRIBUTE: + return visitor.visitPhysicalAttribute(); + case LOCATION_ADDRESS_STREET: + return visitor.visitLocationAddressStreet(); + case MEDICAL_PROCESS: + return visitor.visitMedicalProcess(); + case LOCATION_ADDRESS: + return visitor.visitLocationAddress(); + case FILENAME: + return visitor.visitFilename(); + case DOB: + return visitor.visitDob(); + case ORGANIZATION_MEDICAL_FACILITY: + return visitor.visitOrganizationMedicalFacility(); + case ROUTING_NUMBER: + return visitor.visitRoutingNumber(); + case HEALTHCARE_NUMBER: + return visitor.visitHealthcareNumber(); + case GENDER: + return visitor.visitGender(); + case NAME: + return visitor.visitName(); + case DRUG: + return visitor.visitDrug(); + case NONE: + return visitor.visitNone(); + case DATE_INTERVAL: + return visitor.visitDateInterval(); + case MARITAL_STATUS: + return visitor.visitMaritalStatus(); + case CORPORATE_ACTION: + return visitor.visitCorporateAction(); + case AGE: + return visitor.visitAge(); + case CVV: + return visitor.visitCvv(); + case NAME_GIVEN: + return visitor.visitNameGiven(); + case DATE: + return visitor.visitDate(); + case DAY: + return visitor.visitDay(); + case EFFECT: + return visitor.visitEffect(); + case MEDICAL_CODE: + return visitor.visitMedicalCode(); + case NUMERICAL_PII: + return visitor.visitNumericalPii(); + case TREND: + return visitor.visitTrend(); + case INJURY: + return visitor.visitInjury(); + case DRIVER_LICENSE: + return visitor.visitDriverLicense(); + case ALL: + return visitor.visitAll(); + case ORGANIZATION_ID: + return visitor.visitOrganizationId(); + case PASSWORD: + return visitor.visitPassword(); + case DOSE: + return visitor.visitDose(); + case NAME_FAMILY: + return visitor.visitNameFamily(); + case MONEY: + return visitor.visitMoney(); + case URL: + return visitor.visitUrl(); + case LOCATION_COORDINATE: + return visitor.visitLocationCoordinate(); + case FINANCIAL_METRIC: + return visitor.visitFinancialMetric(); + case ORGANIZATION: + return visitor.visitOrganization(); + case IP_ADDRESS: + return visitor.visitIpAddress(); + case BLOOD_TYPE: + return visitor.visitBloodType(); + case MONTH: + return visitor.visitMonth(); + case CREDIT_CARD: + return visitor.visitCreditCard(); + case ACCOUNT_NUMBER: + return visitor.visitAccountNumber(); + case CREDIT_CARD_EXPIRATION: + return visitor.visitCreditCardExpiration(); + case SSN: + return visitor.visitSsn(); + case EMAIL_ADDRESS: + return visitor.visitEmailAddress(); + case STATISTICS: + return visitor.visitStatistics(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static RedactionLevelEntityName valueOf(String value) { + switch (value) { + case "PHONE_NUMBER": + return PHONE_NUMBER; + case "USERNAME": + return USERNAME; + case "VEHICLE_ID": + return VEHICLE_ID; + case "RELIGION": + return RELIGION; + case "ORIGIN": + return ORIGIN; + case "PASSPORT_NUMBER": + return PASSPORT_NUMBER; + case "YEAR": + return YEAR; + case "CONDITION": + return CONDITION; + case "LOCATION": + return LOCATION; + case "LOCATION_CITY": + return LOCATION_CITY; + case "LOCATION_COUNTRY": + return LOCATION_COUNTRY; + case "PROJECT": + return PROJECT; + case "LOCATION_ZIP": + return LOCATION_ZIP; + case "NAME_MEDICAL_PROFESSIONAL": + return NAME_MEDICAL_PROFESSIONAL; + case "BANK_ACCOUNT": + return BANK_ACCOUNT; + case "OCCUPATION": + return OCCUPATION; + case "TIME": + return TIME; + case "LOCATION_STATE": + return LOCATION_STATE; + case "EVENT": + return EVENT; + case "POLITICAL_AFFILIATION": + return POLITICAL_AFFILIATION; + case "LANGUAGE": + return LANGUAGE; + case "ZODIAC_SIGN": + return ZODIAC_SIGN; + case "PRODUCT": + return PRODUCT; + case "SEXUALITY": + return SEXUALITY; + case "DURATION": + return DURATION; + case "PHYSICAL_ATTRIBUTE": + return PHYSICAL_ATTRIBUTE; + case "LOCATION_ADDRESS_STREET": + return LOCATION_ADDRESS_STREET; + case "MEDICAL_PROCESS": + return MEDICAL_PROCESS; + case "LOCATION_ADDRESS": + return LOCATION_ADDRESS; + case "FILENAME": + return FILENAME; + case "DOB": + return DOB; + case "ORGANIZATION_MEDICAL_FACILITY": + return ORGANIZATION_MEDICAL_FACILITY; + case "ROUTING_NUMBER": + return ROUTING_NUMBER; + case "HEALTHCARE_NUMBER": + return HEALTHCARE_NUMBER; + case "GENDER": + return GENDER; + case "NAME": + return NAME; + case "DRUG": + return DRUG; + case "NONE": + return NONE; + case "DATE_INTERVAL": + return DATE_INTERVAL; + case "MARITAL_STATUS": + return MARITAL_STATUS; + case "CORPORATE_ACTION": + return CORPORATE_ACTION; + case "AGE": + return AGE; + case "CVV": + return CVV; + case "NAME_GIVEN": + return NAME_GIVEN; + case "DATE": + return DATE; + case "DAY": + return DAY; + case "EFFECT": + return EFFECT; + case "MEDICAL_CODE": + return MEDICAL_CODE; + case "NUMERICAL_PII": + return NUMERICAL_PII; + case "TREND": + return TREND; + case "INJURY": + return INJURY; + case "DRIVER_LICENSE": + return DRIVER_LICENSE; + case "ALL": + return ALL; + case "ORGANIZATION_ID": + return ORGANIZATION_ID; + case "PASSWORD": + return PASSWORD; + case "DOSE": + return DOSE; + case "NAME_FAMILY": + return NAME_FAMILY; + case "MONEY": + return MONEY; + case "URL": + return URL; + case "LOCATION_COORDINATE": + return LOCATION_COORDINATE; + case "FINANCIAL_METRIC": + return FINANCIAL_METRIC; + case "ORGANIZATION": + return ORGANIZATION; + case "IP_ADDRESS": + return IP_ADDRESS; + case "BLOOD_TYPE": + return BLOOD_TYPE; + case "MONTH": + return MONTH; + case "CREDIT_CARD": + return CREDIT_CARD; + case "ACCOUNT_NUMBER": + return ACCOUNT_NUMBER; + case "CREDIT_CARD_EXPIRATION": + return CREDIT_CARD_EXPIRATION; + case "SSN": + return SSN; + case "EMAIL_ADDRESS": + return EMAIL_ADDRESS; + case "STATISTICS": + return STATISTICS; + default: + return new RedactionLevelEntityName(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + BANK_ACCOUNT, + + CREDIT_CARD, + + CREDIT_CARD_EXPIRATION, + + CVV, + + DATE, + + DATE_INTERVAL, + + DOB, + + DRIVER_LICENSE, + + EMAIL_ADDRESS, + + HEALTHCARE_NUMBER, + + IP_ADDRESS, + + LOCATION, + + NAME, + + NUMERICAL_PII, + + PHONE_NUMBER, + + SSN, + + URL, + + VEHICLE_ID, + + MEDICAL_CODE, + + NAME_FAMILY, + + NAME_GIVEN, + + ACCOUNT_NUMBER, + + EVENT, + + FILENAME, + + GENDER, + + LANGUAGE, + + LOCATION_ADDRESS, + + LOCATION_CITY, + + LOCATION_COORDINATE, + + LOCATION_COUNTRY, + + LOCATION_STATE, + + LOCATION_ZIP, + + MARITAL_STATUS, + + MONEY, + + NAME_MEDICAL_PROFESSIONAL, + + OCCUPATION, + + ORGANIZATION, + + ORGANIZATION_MEDICAL_FACILITY, + + ORIGIN, + + PASSPORT_NUMBER, + + PASSWORD, + + PHYSICAL_ATTRIBUTE, + + POLITICAL_AFFILIATION, + + RELIGION, + + TIME, + + USERNAME, + + ZODIAC_SIGN, + + BLOOD_TYPE, + + CONDITION, + + DOSE, + + DRUG, + + INJURY, + + MEDICAL_PROCESS, + + STATISTICS, + + ROUTING_NUMBER, + + CORPORATE_ACTION, + + FINANCIAL_METRIC, + + PRODUCT, + + TREND, + + DURATION, + + LOCATION_ADDRESS_STREET, + + AGE, + + SEXUALITY, + + EFFECT, + + PROJECT, + + ORGANIZATION_ID, + + DAY, + + MONTH, + + YEAR, + + ALL, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitBankAccount(); + + T visitCreditCard(); + + T visitCreditCardExpiration(); + + T visitCvv(); + + T visitDate(); + + T visitDateInterval(); + + T visitDob(); + + T visitDriverLicense(); + + T visitEmailAddress(); + + T visitHealthcareNumber(); + + T visitIpAddress(); + + T visitLocation(); + + T visitName(); + + T visitNumericalPii(); + + T visitPhoneNumber(); + + T visitSsn(); + + T visitUrl(); + + T visitVehicleId(); + + T visitMedicalCode(); + + T visitNameFamily(); + + T visitNameGiven(); + + T visitAccountNumber(); + + T visitEvent(); + + T visitFilename(); + + T visitGender(); + + T visitLanguage(); + + T visitLocationAddress(); + + T visitLocationCity(); + + T visitLocationCoordinate(); + + T visitLocationCountry(); + + T visitLocationState(); + + T visitLocationZip(); + + T visitMaritalStatus(); + + T visitMoney(); + + T visitNameMedicalProfessional(); + + T visitOccupation(); + + T visitOrganization(); + + T visitOrganizationMedicalFacility(); + + T visitOrigin(); + + T visitPassportNumber(); + + T visitPassword(); + + T visitPhysicalAttribute(); + + T visitPoliticalAffiliation(); + + T visitReligion(); + + T visitTime(); + + T visitUsername(); + + T visitZodiacSign(); + + T visitBloodType(); + + T visitCondition(); + + T visitDose(); + + T visitDrug(); + + T visitInjury(); + + T visitMedicalProcess(); + + T visitStatistics(); + + T visitRoutingNumber(); + + T visitCorporateAction(); + + T visitFinancialMetric(); + + T visitProduct(); + + T visitTrend(); + + T visitDuration(); + + T visitLocationAddressStreet(); + + T visitAge(); + + T visitSexuality(); + + T visitEffect(); + + T visitProject(); + + T visitOrganizationId(); + + T visitDay(); + + T visitMonth(); + + T visitYear(); + + T visitAll(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevelRedactionType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevelRedactionType.java new file mode 100644 index 00000000..5e9b0807 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/RedactionLevelRedactionType.java @@ -0,0 +1,106 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class RedactionLevelRedactionType { + public static final RedactionLevelRedactionType DEFAULT = new RedactionLevelRedactionType(Value.DEFAULT, "DEFAULT"); + + public static final RedactionLevelRedactionType PLAIN_TEXT = + new RedactionLevelRedactionType(Value.PLAIN_TEXT, "PLAIN_TEXT"); + + public static final RedactionLevelRedactionType MASKED = new RedactionLevelRedactionType(Value.MASKED, "MASKED"); + + public static final RedactionLevelRedactionType REDACTED = + new RedactionLevelRedactionType(Value.REDACTED, "REDACTED"); + + private final Value value; + + private final String string; + + RedactionLevelRedactionType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof RedactionLevelRedactionType + && this.string.equals(((RedactionLevelRedactionType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case DEFAULT: + return visitor.visitDefault(); + case PLAIN_TEXT: + return visitor.visitPlainText(); + case MASKED: + return visitor.visitMasked(); + case REDACTED: + return visitor.visitRedacted(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static RedactionLevelRedactionType valueOf(String value) { + switch (value) { + case "DEFAULT": + return DEFAULT; + case "PLAIN_TEXT": + return PLAIN_TEXT; + case "MASKED": + return MASKED; + case "REDACTED": + return REDACTED; + default: + return new RedactionLevelRedactionType(Value.UNKNOWN, value); + } + } + + public enum Value { + DEFAULT, + + REDACTED, + + MASKED, + + PLAIN_TEXT, + + UNKNOWN + } + + public interface Visitor { + T visitDefault(); + + T visitRedacted(); + + T visitMasked(); + + T visitPlainText(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2.java new file mode 100644 index 00000000..b7b8e3e5 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2.java @@ -0,0 +1,198 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileResponseV2.Builder.class) +public final class ReidentifyFileResponseV2 { + private final Optional status; + + private final Optional outputType; + + private final Optional> output; + + private final Optional metrics; + + private final Map additionalProperties; + + private ReidentifyFileResponseV2( + Optional status, + Optional outputType, + Optional> output, + Optional metrics, + Map additionalProperties) { + this.status = status; + this.outputType = outputType; + this.output = output; + this.metrics = metrics; + this.additionalProperties = additionalProperties; + } + + /** + * @return Status of the reidentification request. + */ + @JsonProperty("status") + public Optional getStatus() { + return status; + } + + /** + * @return Data source of the output file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file. + */ + @JsonProperty("outputType") + public Optional getOutputType() { + return outputType; + } + + /** + * @return Details of output files + */ + @JsonProperty("output") + public Optional> getOutput() { + return output; + } + + @JsonProperty("metrics") + public Optional getMetrics() { + return metrics; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileResponseV2 && equalTo((ReidentifyFileResponseV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileResponseV2 other) { + return status.equals(other.status) + && outputType.equals(other.outputType) + && output.equals(other.output) + && metrics.equals(other.metrics); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.status, this.outputType, this.output, this.metrics); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional status = Optional.empty(); + + private Optional outputType = Optional.empty(); + + private Optional> output = Optional.empty(); + + private Optional metrics = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ReidentifyFileResponseV2 other) { + status(other.getStatus()); + outputType(other.getOutputType()); + output(other.getOutput()); + metrics(other.getMetrics()); + return this; + } + + /** + *

Status of the reidentification request.

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

Data source of the output file. BASE64: Base64-encoded file string. SKYFLOW_ID: Reference file by vault ID. PRESIGNED_URL: S3 presigned URL of input file.

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

Details of output files

+ */ + @JsonSetter(value = "output", nulls = Nulls.SKIP) + public Builder output(Optional> output) { + this.output = output; + return this; + } + + public Builder output(List output) { + this.output = Optional.ofNullable(output); + return this; + } + + @JsonSetter(value = "metrics", nulls = Nulls.SKIP) + public Builder metrics(Optional metrics) { + this.metrics = metrics; + return this; + } + + public Builder metrics(Metrics metrics) { + this.metrics = Optional.ofNullable(metrics); + return this; + } + + public ReidentifyFileResponseV2 build() { + return new ReidentifyFileResponseV2(status, outputType, output, metrics, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2OutputType.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2OutputType.java new file mode 100644 index 00000000..ad4ea20f --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2OutputType.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class ReidentifyFileResponseV2OutputType { + public static final ReidentifyFileResponseV2OutputType BASE64 = + new ReidentifyFileResponseV2OutputType(Value.BASE64, "BASE64"); + + public static final ReidentifyFileResponseV2OutputType SKYFLOW_ID = + new ReidentifyFileResponseV2OutputType(Value.SKYFLOW_ID, "SKYFLOW_ID"); + + public static final ReidentifyFileResponseV2OutputType PRESIGNED_URL = + new ReidentifyFileResponseV2OutputType(Value.PRESIGNED_URL, "PRESIGNED_URL"); + + private final Value value; + + private final String string; + + ReidentifyFileResponseV2OutputType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ReidentifyFileResponseV2OutputType + && this.string.equals(((ReidentifyFileResponseV2OutputType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BASE64: + return visitor.visitBase64(); + case SKYFLOW_ID: + return visitor.visitSkyflowId(); + case PRESIGNED_URL: + return visitor.visitPresignedUrl(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ReidentifyFileResponseV2OutputType valueOf(String value) { + switch (value) { + case "BASE64": + return BASE64; + case "SKYFLOW_ID": + return SKYFLOW_ID; + case "PRESIGNED_URL": + return PRESIGNED_URL; + default: + return new ReidentifyFileResponseV2OutputType(Value.UNKNOWN, value); + } + } + + public enum Value { + BASE64, + + SKYFLOW_ID, + + PRESIGNED_URL, + + UNKNOWN + } + + public interface Visitor { + T visitBase64(); + + T visitSkyflowId(); + + T visitPresignedUrl(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2Status.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2Status.java new file mode 100644 index 00000000..250bd1a9 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyFileResponseV2Status.java @@ -0,0 +1,119 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class ReidentifyFileResponseV2Status { + public static final ReidentifyFileResponseV2Status IN_PROGRESS = + new ReidentifyFileResponseV2Status(Value.IN_PROGRESS, "IN_PROGRESS"); + + public static final ReidentifyFileResponseV2Status QUEUED = + new ReidentifyFileResponseV2Status(Value.QUEUED, "QUEUED"); + + public static final ReidentifyFileResponseV2Status SUCCESS = + new ReidentifyFileResponseV2Status(Value.SUCCESS, "SUCCESS"); + + public static final ReidentifyFileResponseV2Status UNKNOWN = + new ReidentifyFileResponseV2Status(Value.UNKNOWN, "UNKNOWN"); + + public static final ReidentifyFileResponseV2Status FAILED = + new ReidentifyFileResponseV2Status(Value.FAILED, "FAILED"); + + private final Value value; + + private final String string; + + ReidentifyFileResponseV2Status(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ReidentifyFileResponseV2Status + && this.string.equals(((ReidentifyFileResponseV2Status) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case IN_PROGRESS: + return visitor.visitInProgress(); + case QUEUED: + return visitor.visitQueued(); + case SUCCESS: + return visitor.visitSuccess(); + case UNKNOWN: + return visitor.visitUnknown(); + case FAILED: + return visitor.visitFailed(); + case _UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ReidentifyFileResponseV2Status valueOf(String value) { + switch (value) { + case "IN_PROGRESS": + return IN_PROGRESS; + case "QUEUED": + return QUEUED; + case "SUCCESS": + return SUCCESS; + case "UNKNOWN": + return UNKNOWN; + case "FAILED": + return FAILED; + default: + return new ReidentifyFileResponseV2Status(Value._UNKNOWN, value); + } + } + + public enum Value { + UNKNOWN, + + FAILED, + + SUCCESS, + + IN_PROGRESS, + + QUEUED, + + _UNKNOWN + } + + public interface Visitor { + T visitUnknown(); + + T visitFailed(); + + T visitSuccess(); + + T visitInProgress(); + + T visitQueued(); + + T visitUnknown(String unknownType); + } +} diff --git a/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyStringResponseV2.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyStringResponseV2.java new file mode 100644 index 00000000..2c836067 --- /dev/null +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/ReidentifyStringResponseV2.java @@ -0,0 +1,134 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyStringResponseV2.Builder.class) +public final class ReidentifyStringResponseV2 { + private final Optional processedText; + + private final Optional metrics; + + private final Map additionalProperties; + + private ReidentifyStringResponseV2( + Optional processedText, Optional metrics, Map additionalProperties) { + this.processedText = processedText; + this.metrics = metrics; + this.additionalProperties = additionalProperties; + } + + /** + * @return Reidentified text. + */ + @JsonProperty("processedText") + public Optional getProcessedText() { + return processedText; + } + + @JsonProperty("metrics") + public Optional getMetrics() { + return metrics; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyStringResponseV2 && equalTo((ReidentifyStringResponseV2) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyStringResponseV2 other) { + return processedText.equals(other.processedText) && metrics.equals(other.metrics); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.processedText, this.metrics); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional processedText = Optional.empty(); + + private Optional metrics = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ReidentifyStringResponseV2 other) { + processedText(other.getProcessedText()); + metrics(other.getMetrics()); + return this; + } + + /** + *

Reidentified text.

+ */ + @JsonSetter(value = "processedText", nulls = Nulls.SKIP) + public Builder processedText(Optional processedText) { + this.processedText = processedText; + return this; + } + + public Builder processedText(String processedText) { + this.processedText = Optional.ofNullable(processedText); + return this; + } + + @JsonSetter(value = "metrics", nulls = Nulls.SKIP) + public Builder metrics(Optional metrics) { + this.metrics = metrics; + return this; + } + + public Builder metrics(Metrics metrics) { + this.metrics = Optional.ofNullable(metrics); + return this; + } + + public ReidentifyStringResponseV2 build() { + return new ReidentifyStringResponseV2(processedText, metrics, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ShiftDates.java b/common/src/main/java/com/skyflow/generated/detect/rest/types/TransformationShiftDates.java similarity index 50% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/ShiftDates.java rename to common/src/main/java/com/skyflow/generated/detect/rest/types/TransformationShiftDates.java index 37ef8cdf..78879313 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ShiftDates.java +++ b/common/src/main/java/com/skyflow/generated/detect/rest/types/TransformationShiftDates.java @@ -1,64 +1,58 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; +package com.skyflow.generated.detect.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.*; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = ShiftDates.Builder.class) -public final class ShiftDates { +@JsonDeserialize(builder = TransformationShiftDates.Builder.class) +public final class TransformationShiftDates { private final Optional minDays; private final Optional maxDays; - private final Optional> entityTypes; - private final Map additionalProperties; - private ShiftDates( - Optional minDays, - Optional maxDays, - Optional> entityTypes, - Map additionalProperties) { + private TransformationShiftDates( + Optional minDays, Optional maxDays, Map additionalProperties) { this.minDays = minDays; this.maxDays = maxDays; - this.entityTypes = entityTypes; this.additionalProperties = additionalProperties; } /** - * @return Minimum number of days to shift the date by. + * @return Minimum number of days to shift dates. */ - @JsonProperty("min_days") + @JsonProperty("minDays") public Optional getMinDays() { return minDays; } /** - * @return Maximum number of days to shift the date by. + * @return Maximum number of days to shift dates. */ - @JsonProperty("max_days") + @JsonProperty("maxDays") public Optional getMaxDays() { return maxDays; } - /** - * @return Entity types to shift dates for. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof ShiftDates && equalTo((ShiftDates) other); + return other instanceof TransformationShiftDates && equalTo((TransformationShiftDates) other); } @JsonAnyGetter @@ -66,16 +60,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(ShiftDates other) { - return minDays.equals(other.minDays) && maxDays.equals(other.maxDays) && entityTypes.equals(other.entityTypes); + private boolean equalTo(TransformationShiftDates other) { + return minDays.equals(other.minDays) && maxDays.equals(other.maxDays); } - @Override + @java.lang.Override public int hashCode() { - return Objects.hash(this.minDays, this.maxDays, this.entityTypes); + return Objects.hash(this.minDays, this.maxDays); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -90,24 +84,21 @@ public static final class Builder { private Optional maxDays = Optional.empty(); - private Optional> entityTypes = Optional.empty(); - @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} - public Builder from(ShiftDates other) { + public Builder from(TransformationShiftDates other) { minDays(other.getMinDays()); maxDays(other.getMaxDays()); - entityTypes(other.getEntityTypes()); return this; } /** - *

Minimum number of days to shift the date by.

+ *

Minimum number of days to shift dates.

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

Maximum number of days to shift the date by.

+ *

Maximum number of days to shift dates.

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

Entity types to shift dates for.

- */ - @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) - public Builder entityTypes(Optional> entityTypes) { - this.entityTypes = entityTypes; - return this; + public TransformationShiftDates build() { + return new TransformationShiftDates(minDays, maxDays, additionalProperties); } - public Builder entityTypes(List entityTypes) { - this.entityTypes = Optional.ofNullable(entityTypes); + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); return this; } - public ShiftDates build() { - return new ShiftDates(minDays, maxDays, entityTypes, additionalProperties); + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/common/src/main/java/com/skyflow/logs/ErrorLogs.java b/common/src/main/java/com/skyflow/logs/ErrorLogs.java index 418d08bc..2051cedc 100644 --- a/common/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/common/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -1,6 +1,34 @@ package com.skyflow.logs; public enum ErrorLogs { + CHECK_GUARDRAILS_REQUEST_NULL("Invalid %s1 request. CheckGuardrails request can not be null."), + INVALID_TEXT_IN_CHECK_GUARDRAILS("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), + CHECK_GUARDRAILS_REQUEST_REJECTED("Check guardrails request resulted in failure."), + GET_RUN_REQUEST_NULL("Invalid %s1 request. GetRun request can not be null."), + INVALID_RUN_ID_IN_GET_RUN("Invalid %s1 request. The runId field is required and must be a non-empty string. Specify a valid run id."), + GET_RUN_REQUEST_REJECTED("Get run request resulted in failure."), + DEIDENTIFY_STRING_REQUEST_NULL("Invalid %s1 request. DeidentifyString request can not be null."), + INVALID_TEXT_IN_DEIDENTIFY_STRING("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), + DEIDENTIFY_STRING_REQUEST_REJECTED("DeIdentify string request resulted in failure."), + REIDENTIFY_STRING_REQUEST_NULL("Invalid %s1 request. ReidentifyString request can not be null."), + INVALID_TEXT_IN_REIDENTIFY_STRING("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), + REIDENTIFY_STRING_REQUEST_REJECTED("ReIdentify string request resulted in failure."), + DEIDENTIFY_FILE_REQUEST_NULL("Invalid %s1 request. DeidentifyFile request can not be null."), + INVALID_DATA_SOURCE_IN_DEIDENTIFY_FILE("Invalid %s1 request. The dataSource field is required unless a file is supplied."), + INVALID_VALUE_IN_DEIDENTIFY_FILE("Invalid %s1 request. The value field is required and must be a non-empty string unless a file is supplied."), + MULTIPLE_FILE_SOURCES_IN_DEIDENTIFY_FILE("Invalid %s1 request. Specify either value or file, not both."), + FILE_NOT_FOUND_IN_DEIDENTIFY_FILE("Invalid %s1 request. The file to deidentify was not found."), + FAILED_TO_ENCODE_FILE_IN_DEIDENTIFY_FILE("Invalid %s1 request. Failed to read and encode the file to deidentify."), + INVALID_WAIT_TIME_IN_POLL_OPTIONS("Invalid %s1 request. waitTime in pollOptions must be between 1 and 300."), + INVALID_MAX_ATTEMPTS_IN_POLL_OPTIONS("Invalid %s1 request. maxAttempts in pollOptions must be between 1 and 23."), + OUTPUT_DIRECTORY_WITHOUT_POLL_OPTIONS("Invalid %s1 request. outputDirectory requires pollOptions."), + DEIDENTIFY_FILE_REQUEST_REJECTED("DeIdentify file request resulted in failure."), + OUTPUT_DIRECTORY_NOT_CREATED("Could not create output directory %s1."), + OUTPUT_FILE_NOT_WRITTEN("Could not write processed output to %s1."), + REIDENTIFY_FILE_REQUEST_NULL("Invalid %s1 request. ReidentifyFile request can not be null."), + INVALID_DATA_SOURCE_IN_REIDENTIFY_FILE("Invalid %s1 request. The dataSource field is required. Specify BASE64, SKYFLOW_ID or PRESIGNED_URL."), + INVALID_VALUE_IN_REIDENTIFY_FILE("Invalid %s1 request. The value field is required and must be a non-empty string. Specify the base64 content, skyflow id or presigned URL of the file."), + REIDENTIFY_FILE_REQUEST_REJECTED("ReIdentify file request resulted in failure."), // Client initialization VAULT_CONFIG_EXISTS("Vault config with vault ID %s1 already exists."), VAULT_CONFIG_DOES_NOT_EXIST("Vault config with vault ID %s1 doesn't exist."), @@ -184,7 +212,6 @@ public enum ErrorLogs { REIDENTIFY_TEXT_REQUEST_NULL("Invalid %s1 request. ReidentifyText request can not be null."), INVALID_TEXT_IN_REIDENTIFY("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), REIDENTIFY_TEXT_REQUEST_REJECTED("ReIdentify text request resulted in failure."), - DEIDENTIFY_FILE_REQUEST_REJECTED("DeIdentify file request resulted in failure."), GET_DETECT_RUN_REQUEST_REJECTED("Get detect run request resulted in failure."), INVALID_NULL_FILE_IN_DEIDENTIFY_FILE("Invalid %s1 request. The file field is required and must not be null. Specify a valid file."), FILE_NOT_FOUND_TO_DEIDENTIFY("Invalid %s1 request. The file field is required and must not be empty. Specify a valid file."), diff --git a/common/src/main/java/com/skyflow/logs/InfoLogs.java b/common/src/main/java/com/skyflow/logs/InfoLogs.java index b4045229..3c332232 100644 --- a/common/src/main/java/com/skyflow/logs/InfoLogs.java +++ b/common/src/main/java/com/skyflow/logs/InfoLogs.java @@ -1,6 +1,37 @@ package com.skyflow.logs; public enum InfoLogs { + CHECK_GUARDRAILS_TRIGGERED("Check guardrails method triggered."), + VALIDATE_CHECK_GUARDRAILS_REQUEST("Validating check guardrails request."), + CHECK_GUARDRAILS_REQUEST_RESOLVED("Check guardrails request resolved."), + CHECK_GUARDRAILS_SUCCESS("Guardrails check completed."), + GET_RUN_TRIGGERED("Get run method triggered."), + VALIDATE_GET_RUN_REQUEST("Validating get run request."), + GET_RUN_REQUEST_RESOLVED("Get run request resolved."), + GET_RUN_SUCCESS("Detect run retrieved."), + DEIDENTIFY_STRING_TRIGGERED("DeIdentify string method triggered."), + VALIDATE_DEIDENTIFY_STRING_REQUEST("Validating deidentify string request."), + DEIDENTIFY_STRING_REQUEST_RESOLVED("DeIdentify string request resolved."), + DEIDENTIFY_STRING_SUCCESS("String data de-identified."), + REIDENTIFY_STRING_TRIGGERED("ReIdentify string method triggered."), + VALIDATE_REIDENTIFY_STRING_REQUEST("Validating reidentify string request."), + REIDENTIFY_STRING_REQUEST_RESOLVED("ReIdentify string request resolved."), + REIDENTIFY_STRING_SUCCESS("String data re-identified."), + DEIDENTIFY_FILE_TRIGGERED("DeIdentify file method triggered."), + VALIDATE_DEIDENTIFY_FILE_REQUEST("Validating deidentify file request."), + DEIDENTIFY_FILE_REQUEST_RESOLVED("DeIdentify file request resolved."), + DEIDENTIFY_FILE_RUN_SUBMITTED("DeIdentify file run %s1 submitted; retrieve it with getRun."), + DEIDENTIFY_FILE_SUCCESS("File data de-identified."), + POLL_RUN_STARTED("Polling run %s1 for up to %s2 seconds and %s3 attempts."), + POLL_RUN_TERMINAL("Run %s1 reached status %s2 after %s3 attempts."), + POLL_RUN_BUDGET_EXHAUSTED("Run %s1 still %s2 after %s3 attempts and %s4 seconds; returning run id."), + POLL_RUN_INTERRUPTED("Polling of run %s1 interrupted while %s2; returning run id."), + OUTPUT_FILE_WRITTEN("Processed output written to %s1."), + OUTPUT_NOT_WRITTEN_FOR_OUTPUT_TYPE("Outputs delivered as %s1 are not written to disk."), + REIDENTIFY_FILE_TRIGGERED("ReIdentify file method triggered."), + VALIDATE_REIDENTIFY_FILE_REQUEST("Validating reidentify file request."), + REIDENTIFY_FILE_REQUEST_RESOLVED("ReIdentify file request resolved."), + REIDENTIFY_FILE_SUCCESS("File data re-identified."), // Client initialization CLIENT_INITIALIZED("Initialized skyflow client."), VALIDATING_VAULT_CONFIG("Validating vault config."), @@ -91,10 +122,6 @@ public enum InfoLogs { VALIDATE_REIDENTIFY_TEXT_REQUEST("Validating reidentify text request."), REIDENTIFY_TEXT_TRIGGERED("ReIdentify text method triggered."), REIDENTIFY_TEXT_REQUEST_RESOLVED("ReIdentify text request resolved."), - DEIDENTIFY_FILE_TRIGGERED("DeIdentify file method triggered."), - VALIDATE_DEIDENTIFY_FILE_REQUEST("Validating deidentify file request."), - DEIDENTIFY_FILE_REQUEST_RESOLVED("DeIdentify file request resolved."), - DEIDENTIFY_FILE_SUCCESS("File deidentified successfully."), GET_DETECT_RUN_TRIGGERED("Get detect run method triggered."), VALIDATE_GET_DETECT_RUN_REQUEST("Validating get detect run request."), REIDENTIFY_TEXT_SUCCESS("Text data re-identified."), diff --git a/common/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/common/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index 882df51c..a98f4e3a 100644 --- a/common/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/common/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -2,7 +2,7 @@ import com.google.gson.*; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.auth.rest.ApiClient; import com.skyflow.generated.auth.rest.ApiClientBuilder; @@ -56,7 +56,7 @@ private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( try { if (credentialsFile == null) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidCredentials.getMessage()); } FileReader reader = new FileReader(String.valueOf(credentialsFile)); try { @@ -68,11 +68,11 @@ private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( } catch (JsonSyntaxException | IllegalStateException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE_FORMAT.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseUtils.parameterizedString( - ErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getPath())); + BaseErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getPath())); } catch (FileNotFoundException e) { LogUtil.printErrorLog(ErrorLogs.CREDENTIALS_FILE_NOT_FOUND.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseUtils.parameterizedString( - ErrorMessage.FileNotFound.getMessage(), credentialsFile.getPath())); + BaseErrorMessage.FileNotFound.getMessage(), credentialsFile.getPath())); } } @@ -83,14 +83,14 @@ private static V1GetAuthTokenResponse generateBearerTokenFromCredentialString( try { if (credentials == null || credentials.isEmpty()) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidCredentials.getMessage()); } JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); } catch (JsonSyntaxException | IllegalStateException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING_FORMAT.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - ErrorMessage.CredentialsStringInvalidJson.getMessage()); + BaseErrorMessage.CredentialsStringInvalidJson.getMessage()); } } @@ -101,7 +101,7 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( JsonElement privateKey = credentials.get("privateKey"); if (privateKey == null) { LogUtil.printErrorLog(ErrorLogs.PRIVATE_KEY_IS_REQUIRED.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingPrivateKey.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MissingPrivateKey.getMessage()); } // Accept both new-form keys (clientId/keyId/tokenUri) and legacy all-caps form for migration @@ -114,7 +114,7 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( } if (clientId == null) { LogUtil.printErrorLog(ErrorLogs.CLIENT_ID_IS_REQUIRED.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingClientId.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MissingClientId.getMessage()); } JsonElement keyId = credentials.get("keyId"); @@ -126,7 +126,7 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( } if (keyId == null) { LogUtil.printErrorLog(ErrorLogs.KEY_ID_IS_REQUIRED.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingKeyId.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MissingKeyId.getMessage()); } JsonElement tokenUri = credentials.get("tokenUri"); @@ -138,7 +138,7 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( } if (tokenUri == null) { LogUtil.printErrorLog(ErrorLogs.TOKEN_URI_IS_REQUIRED.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingTokenUri.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MissingTokenUri.getMessage()); } PrivateKey pvtKey = BaseUtils.getPrivateKeyFromPem(privateKey.getAsString()); @@ -160,7 +160,7 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( return authenticationApi.authenticationServiceGetAuthToken(authTokenBuilder.build()); } catch (MalformedURLException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_TOKEN_URI.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTokenUri.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidTokenUri.getMessage()); } catch (ApiClientApiException e) { String bodyString = GSON.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.BEARER_TOKEN_REJECTED.getLog()); @@ -218,7 +218,7 @@ public synchronized String getBearerToken() throws SkyflowException { private static String extractAccessToken(V1GetAuthTokenResponse response) throws SkyflowException { if (!response.getAccessToken().isPresent()) { LogUtil.printErrorLog(ErrorLogs.MISSING_ACCESS_TOKEN.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingAccessToken.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MissingAccessToken.getMessage()); } return response.getAccessToken().get(); } diff --git a/common/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/common/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index 630a0aee..a4a2c57d 100644 --- a/common/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ b/common/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -5,7 +5,7 @@ import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; @@ -49,7 +49,7 @@ private static List generateSignedTokenFromCredentialsF try { if (credentialsFile == null) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidCredentials.getMessage()); } FileReader reader = new FileReader(String.valueOf(credentialsFile)); try { @@ -61,11 +61,11 @@ private static List generateSignedTokenFromCredentialsF } catch (JsonSyntaxException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE_FORMAT.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseUtils.parameterizedString( - ErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getPath())); + BaseErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getPath())); } catch (FileNotFoundException e) { LogUtil.printErrorLog(ErrorLogs.CREDENTIALS_FILE_NOT_FOUND.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseUtils.parameterizedString( - ErrorMessage.FileNotFound.getMessage(), credentialsFile.getPath())); + BaseErrorMessage.FileNotFound.getMessage(), credentialsFile.getPath())); } return responseToken; } @@ -78,14 +78,14 @@ private static List generateSignedTokensFromCredentials try { if (credentials == null || credentials.isEmpty()) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidCredentials.getMessage()); } JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); responseToken = generateSignedTokensFromCredentials(serviceAccountCredentials, dataTokens, timeToLive, context); } catch (JsonSyntaxException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING_FORMAT.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - ErrorMessage.CredentialsStringInvalidJson.getMessage()); + BaseErrorMessage.CredentialsStringInvalidJson.getMessage()); } return responseToken; } @@ -98,7 +98,7 @@ private static List generateSignedTokensFromCredentials JsonElement privateKey = credentials.get("privateKey"); if (privateKey == null) { LogUtil.printErrorLog(ErrorLogs.PRIVATE_KEY_IS_REQUIRED.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingPrivateKey.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MissingPrivateKey.getMessage()); } // Accept both new-form keys (clientId/keyId) and legacy all-caps form for migration @@ -111,7 +111,7 @@ private static List generateSignedTokensFromCredentials } if (clientId == null) { LogUtil.printErrorLog(ErrorLogs.CLIENT_ID_IS_REQUIRED.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingClientId.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MissingClientId.getMessage()); } JsonElement keyId = credentials.get("keyId"); @@ -123,7 +123,7 @@ private static List generateSignedTokensFromCredentials } if (keyId == null) { LogUtil.printErrorLog(ErrorLogs.KEY_ID_IS_REQUIRED.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingKeyId.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MissingKeyId.getMessage()); } PrivateKey pvtKey = BaseUtils.getPrivateKeyFromPem(privateKey.getAsString()); signedDataTokens = getSignedToken( diff --git a/common/src/main/java/com/skyflow/serviceaccount/util/Token.java b/common/src/main/java/com/skyflow/serviceaccount/util/Token.java index 0359d944..19edf0c8 100644 --- a/common/src/main/java/com/skyflow/serviceaccount/util/Token.java +++ b/common/src/main/java/com/skyflow/serviceaccount/util/Token.java @@ -5,7 +5,7 @@ import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; @@ -29,7 +29,7 @@ public static boolean isExpired(String token) { JsonElement exp = decoded(token).get("exp"); if (exp == null) { LogUtil.printErrorLog(ErrorLogs.INVALID_BEARER_TOKEN.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtDecodeError.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.JwtDecodeError.getMessage()); } expiryTime = exp.getAsLong(); @@ -44,14 +44,14 @@ static JsonObject decoded(String encodedToken) throws JsonSyntaxException, Skyfl String[] split = encodedToken.split("\\."); if (split.length < 3) { LogUtil.printErrorLog(ErrorLogs.INVALID_BEARER_TOKEN.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtDecodeError.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.JwtDecodeError.getMessage()); } try { byte[] decodedBytes = Base64.getUrlDecoder().decode(split[1]); return JsonParser.parseString(new String(decodedBytes, StandardCharsets.UTF_8)).getAsJsonObject(); } catch (IllegalArgumentException | IllegalStateException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_BEARER_TOKEN.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtDecodeError.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.JwtDecodeError.getMessage()); } } } diff --git a/common/src/main/java/com/skyflow/utils/BaseConstants.java b/common/src/main/java/com/skyflow/utils/BaseConstants.java index e9946a40..8d0ea8d8 100644 --- a/common/src/main/java/com/skyflow/utils/BaseConstants.java +++ b/common/src/main/java/com/skyflow/utils/BaseConstants.java @@ -27,6 +27,7 @@ public class BaseConstants { public static final String SDK_METRIC_RUNTIME_DETAILS_PREFIX = "Java@"; public static final String SDK_AUTH_HEADER_KEY = "x-skyflow-authorization"; public static final String SDK_METRICS_HEADER_KEY = "sky-metadata"; + public static final String PROCESSED_FILE_NAME_PREFIX = "processed-"; public static final String REQUEST_ID_HEADER_KEY = "x-request-id"; public static final String ERROR_FROM_CLIENT_HEADER_KEY = "error-from-client"; diff --git a/common/src/main/java/com/skyflow/utils/BaseUtils.java b/common/src/main/java/com/skyflow/utils/BaseUtils.java index e536c111..8e076c1b 100644 --- a/common/src/main/java/com/skyflow/utils/BaseUtils.java +++ b/common/src/main/java/com/skyflow/utils/BaseUtils.java @@ -15,7 +15,7 @@ import com.skyflow.config.BaseCredentials; import com.skyflow.enums.Env; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; @@ -87,11 +87,11 @@ public static PrivateKey getPrivateKeyFromPem(String pemKey) throws SkyflowExcep privateKey = parsePkcs8PrivateKey(Base64.getDecoder().decode(privateKeyContent)); } catch (IllegalArgumentException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_KEY_SPEC.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidKeySpec.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidKeySpec.getMessage()); } } else { LogUtil.printErrorLog(ErrorLogs.JWT_INVALID_FORMAT.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtInvalidFormat.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.JwtInvalidFormat.getMessage()); } return privateKey; } @@ -165,10 +165,10 @@ private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws Skyflow privateKey = keyFactory.generatePrivate(keySpec); } catch (NoSuchAlgorithmException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_ALGORITHM.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidAlgorithm.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidAlgorithm.getMessage()); } catch (InvalidKeySpecException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_KEY_SPEC.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidKeySpec.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidKeySpec.getMessage()); } return privateKey; } diff --git a/common/src/main/java/com/skyflow/utils/validations/BaseValidations.java b/common/src/main/java/com/skyflow/utils/validations/BaseValidations.java index b542589a..89bfb501 100644 --- a/common/src/main/java/com/skyflow/utils/validations/BaseValidations.java +++ b/common/src/main/java/com/skyflow/utils/validations/BaseValidations.java @@ -2,7 +2,7 @@ import com.skyflow.config.BaseCredentials; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.utils.BaseConstants; @@ -21,7 +21,7 @@ public class BaseValidations { public static void validateCredentials(BaseCredentials credentials) throws SkyflowException { if (credentials == null) { LogUtil.printErrorLog(ErrorLogs.CREDENTIALS_IS_NULL.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.NullCredentials.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.NullCredentials.getMessage()); } int nonNullMembers = 0; String path = credentials.getPath(); @@ -39,38 +39,38 @@ public static void validateCredentials(BaseCredentials credentials) throws Skyfl if (nonNullMembers > 1) { LogUtil.printErrorLog(ErrorLogs.MULTIPLE_TOKEN_GENERATION_MEANS_PASSED.getLog()); throw new SkyflowException( - ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MultipleTokenGenerationMeansPassed.getMessage() + ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MultipleTokenGenerationMeansPassed.getMessage() ); } else if (nonNullMembers < 1) { LogUtil.printErrorLog(ErrorLogs.NO_TOKEN_GENERATION_MEANS_PASSED.getLog()); throw new SkyflowException( - ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.NoTokenGenerationMeansPassed.getMessage() + ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.NoTokenGenerationMeansPassed.getMessage() ); } else if (path != null && path.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_CREDENTIALS_PATH.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentialFilePath.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyCredentialFilePath.getMessage()); } else if (credentialsString != null && credentialsString.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_CREDENTIALS_STRING.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentialsString.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyCredentialsString.getMessage()); } else if (token != null && token.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_TOKEN_VALUE.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyToken.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyToken.getMessage()); } else if (apiKey != null) { if (apiKey.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_API_KEY_VALUE.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyApikey.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyApikey.getMessage()); } else { Pattern pattern = Pattern.compile(BaseConstants.API_KEY_REGEX); Matcher matcher = pattern.matcher(apiKey); if (!matcher.matches()) { LogUtil.printErrorLog(ErrorLogs.INVALID_API_KEY.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidApikey.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidApikey.getMessage()); } } } else if (roles != null) { if (roles.isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_ROLES.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRoles.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyRoles.getMessage()); } else { for (int index = 0; index < roles.size(); index++) { String role = roles.get(index); @@ -78,7 +78,7 @@ public static void validateCredentials(BaseCredentials credentials) throws Skyfl LogUtil.printErrorLog(BaseUtils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_ROLE_IN_ROLES.getLog(), Integer.toString(index) )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRoleInRoles.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyRoleInRoles.getMessage()); } } } @@ -88,13 +88,13 @@ public static void validateCredentials(BaseCredentials credentials) throws Skyfl String ctxStr = (String) context; if (ctxStr.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_OR_NULL_CONTEXT.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyContext.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyContext.getMessage()); } } else if (context instanceof Map) { Map ctxMap = (Map) context; if (ctxMap.isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_OR_NULL_CONTEXT.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyContext.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyContext.getMessage()); } Pattern ctxKeyPattern = Pattern.compile(BaseConstants.CONTEXT_KEY_REGEX); for (Object key : ctxMap.keySet()) { @@ -103,12 +103,12 @@ public static void validateCredentials(BaseCredentials credentials) throws Skyfl LogUtil.printErrorLog(BaseUtils.parameterizedString( ErrorLogs.INVALID_CONTEXT_MAP_KEY.getLog(), keyStr)); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - BaseUtils.parameterizedString(ErrorMessage.InvalidContextMapKey.getMessage(), keyStr)); + BaseUtils.parameterizedString(BaseErrorMessage.InvalidContextMapKey.getMessage(), keyStr)); } } } else { LogUtil.printErrorLog(ErrorLogs.INVALID_CONTEXT_TYPE.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidContextType.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidContextType.getMessage()); } } } diff --git a/common/src/main/java/com/skyflow/vault/controller/BaseDetectController.java b/common/src/main/java/com/skyflow/vault/controller/BaseDetectController.java new file mode 100644 index 00000000..865bd1ff --- /dev/null +++ b/common/src/main/java/com/skyflow/vault/controller/BaseDetectController.java @@ -0,0 +1,452 @@ +package com.skyflow.vault.controller; + +import com.skyflow.BaseVaultClient; +import com.skyflow.config.BaseCredentials; +import com.skyflow.config.BaseVaultConfig; +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.CheckGuardrailsResponse; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyFileResponse; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.DeidentifyStringResponse; +import com.skyflow.detect.GetRunRequest; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.detect.ReidentifyFileResponse; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.detect.ReidentifyStringResponse; +import com.skyflow.detect.internal.DeidentifyFileFlow; +import com.skyflow.detect.internal.DetectRequestMapper; +import com.skyflow.detect.internal.DetectResponseMapper; +import com.skyflow.detect.internal.DetectValidations; +import com.skyflow.detect.internal.ReidentifyFileMapper; +import com.skyflow.detect.internal.ReidentifyFileValidations; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.detect.rest.core.ApiClientApiException; +import com.skyflow.generated.detect.rest.core.ApiClientException; +import com.skyflow.generated.detect.rest.core.ClientOptions; +import com.skyflow.generated.detect.rest.core.Environment; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.core.RequestOptions; +import com.skyflow.generated.detect.rest.resources.filesv2.FilesV2Client; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.DeidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.GetRunV2Request; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.ReidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.resources.guardrailsv2.GuardrailsV2Client; +import com.skyflow.generated.detect.rest.resources.guardrailsv2.requests.DetectGuardrailsRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.StringsV2Client; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.DeidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.ReidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.types.DeidentifyFileResponseV2; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2; +import com.skyflow.generated.detect.rest.types.DetectGuardrailsResponseV2; +import com.skyflow.generated.detect.rest.types.DetectRunsResponseV2; +import com.skyflow.generated.detect.rest.types.ReidentifyFileResponseV2; +import com.skyflow.generated.detect.rest.types.ReidentifyStringResponseV2; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.BaseConstants; +import com.skyflow.utils.logger.LogUtil; + +/** + * Shared implementation of the Skyflow Detect V2 API. Each SDK's {@code DetectController} + * extends this class and supplies only what differs per vault type: how the vault URL is + * resolved, the SDK metrics header, and any vault-level timeout and retry overrides. + * + *

Credentials, bearer-token refresh and the vault configuration come from + * {@link BaseVaultClient}. The generated V2 client is created lazily and rebuilt whenever the + * vault URL or the effective HTTP settings change. + * + * @param the SDK's vault configuration type + */ +public abstract class BaseDetectController extends BaseVaultClient { + private static final String AUTHORIZATION_HEADER = "Authorization"; + private static final String BEARER_PREFIX = "Bearer "; + + private Integer commonTimeoutSeconds; + private Integer commonMaxRetries; + private Long commonInitialRetryDelayMillis; + private Long commonMaxRetryDelayMillis; + + private ClientOptions clientOptions; + private String clientOptionsKey; + private StringsV2Client stringsClient; + private FilesV2Client filesClient; + private GuardrailsV2Client guardrailsClient; + + protected BaseDetectController(V vaultConfig, BaseCredentials credentials) { + super(vaultConfig, credentials); + } + + // ------------------------------------------------------------------ + // Hooks for the concrete SDK controllers + // ------------------------------------------------------------------ + + /** + * @return the vault base URL requests are sent to, for example + * {@code https://.vault.skyflowapis.com} + * @throws SkyflowException if the URL cannot be determined + */ + protected abstract String resolveVaultUrl() throws SkyflowException; + + /** + * @return JSON sent in the {@code sky-metadata} header. Override to report SDK name and version. + */ + protected String getSdkMetrics() { + return "{}"; + } + + /** + * Resolves the bearer token or API key for the next call, refreshing it when expired. + * The default uses the credential chain in {@link BaseVaultClient}. + */ + protected String resolveToken() throws SkyflowException { + setBearerToken(this.vaultConfig.getCredentials()); + return this.token; + } + + /** @return overall call timeout in seconds, or {@code null} for the transport default */ + protected Integer effectiveTimeoutSeconds() { + return commonTimeoutSeconds; + } + + /** @return retries on retryable HTTP statuses, or {@code null} for the transport default */ + protected Integer effectiveMaxRetries() { + return commonMaxRetries; + } + + protected Long effectiveInitialRetryDelayMillis() { + return commonInitialRetryDelayMillis; + } + + protected Long effectiveMaxRetryDelayMillis() { + return commonMaxRetryDelayMillis; + } + + // ------------------------------------------------------------------ + // Lifecycle, driven by each SDK's Skyflow builder. Public because the builders live in + // com.skyflow while this class lives in com.skyflow.vault.controller; applications have + // no reason to call these directly. + // ------------------------------------------------------------------ + + /** Applies client-level credentials; vault-level credentials keep precedence. */ + public void setCommonCredentials(BaseCredentials commonCredentials) throws SkyflowException { + this.commonCredentials = commonCredentials; + prioritiseCredentials(this.vaultConfig.getCredentials()); + onCommonCredentialsUpdated(commonCredentials); + } + + /** + * Called after client-level credentials change. Subclasses that hold other clients (for + * example a V1 delegate) override this to forward the update; the default does nothing. + */ + protected void onCommonCredentialsUpdated(BaseCredentials commonCredentials) throws SkyflowException { + } + + /** Applies client-level timeout and retry settings; vault-level settings keep precedence. */ + public synchronized void setCommonHttpConfig(Integer timeoutSeconds, Integer maxRetries, + Long initialRetryDelayMillis, Long maxRetryDelayMillis) { + this.commonTimeoutSeconds = timeoutSeconds; + this.commonMaxRetries = maxRetries; + this.commonInitialRetryDelayMillis = initialRetryDelayMillis; + this.commonMaxRetryDelayMillis = maxRetryDelayMillis; + invalidateClients(); + } + + /** Replaces the vault configuration, for example after {@code updateVaultConfig}. */ + public synchronized void setVaultConfig(V vaultConfig) throws SkyflowException { + this.vaultConfig = vaultConfig; + invalidateClients(); + } + + /** Forces the vault URL to be resolved again on the next call. */ + public synchronized void refreshVaultUrl() throws SkyflowException { + invalidateClients(); + } + + /** Drops cached generated clients so the next call rebuilds them from current settings. */ + protected synchronized void invalidateClients() { + this.clientOptions = null; + this.clientOptionsKey = null; + this.stringsClient = null; + this.filesClient = null; + this.guardrailsClient = null; + } + + // ------------------------------------------------------------------ + // Detect V2 operations + // ------------------------------------------------------------------ + + /** + * Detects and de-identifies sensitive data in a string. Synchronous. + * + * @param request text plus exactly one of a stored configuration id or an inline configuration + * @return processed text, detected entities and metrics + * @throws SkyflowException on validation failure, credential failure or an API error + */ + public DeidentifyStringResponse deidentifyString(DeidentifyStringRequest request) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_STRING_TRIGGERED.getLog()); + LogUtil.printInfoLog(InfoLogs.VALIDATE_DEIDENTIFY_STRING_REQUEST.getLog()); + DetectValidations.validateDeidentifyStringRequest(request); + String token = resolveToken(); + DeidentifyStringRequestV2 apiRequest = + DetectRequestMapper.toDeidentifyStringRequest(request, this.vaultConfig.getVaultId()); + try { + DeidentifyStringResponseV2 apiResponse = stringsClient().deidentifyStringV2(apiRequest, requestOptions(token)); + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_STRING_REQUEST_RESOLVED.getLog()); + DeidentifyStringResponse response = DetectResponseMapper.toDeidentifyStringResponse(apiResponse); + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_STRING_SUCCESS.getLog()); + return response; + } catch (ApiClientApiException e) { + throw toSkyflowException(e, ErrorLogs.DEIDENTIFY_STRING_REQUEST_REJECTED); + } catch (ApiClientException e) { + LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_STRING_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e); + } + } + + /** + * Replaces tokens in a string with their original values or a redacted rendering. Synchronous. + * + * @param request text containing tokens plus optional per-group redaction rules + * @return re-identified text and metrics + * @throws SkyflowException on validation failure, credential failure or an API error + */ + public ReidentifyStringResponse reidentifyString(ReidentifyStringRequest request) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_STRING_TRIGGERED.getLog()); + LogUtil.printInfoLog(InfoLogs.VALIDATE_REIDENTIFY_STRING_REQUEST.getLog()); + DetectValidations.validateReidentifyStringRequest(request); + String token = resolveToken(); + ReidentifyStringRequestV2 apiRequest = + DetectRequestMapper.toReidentifyStringRequest(request, this.vaultConfig.getVaultId()); + try { + ReidentifyStringResponseV2 apiResponse = stringsClient().reidentifyStringV2(apiRequest, requestOptions(token)); + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_STRING_REQUEST_RESOLVED.getLog()); + ReidentifyStringResponse response = DetectResponseMapper.toReidentifyStringResponse(apiResponse); + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_STRING_SUCCESS.getLog()); + return response; + } catch (ApiClientApiException e) { + throw toSkyflowException(e, ErrorLogs.REIDENTIFY_STRING_REQUEST_REJECTED); + } catch (ApiClientException e) { + LogUtil.printErrorLog(ErrorLogs.REIDENTIFY_STRING_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e); + } + } + + /** + * Detects and de-identifies sensitive data in a file. The API is asynchronous: by default this + * submits the run and returns its id for use with {@link #getRun}. With + * {@link DeidentifyFileRequest#getPollOptions() pollOptions} the SDK polls the run with exponential + * backoff and returns the completed run, or the run id with a non-terminal status if the budget + * runs out. On success, a request built from a local file has its outputs written to disk. + * + * @param request the file (base64, skyflow id, presigned URL, or a local file) plus a stored or inline configuration + * @return run id, and the run's status, outputs and metrics when polled + * @throws SkyflowException on validation failure, credential failure, an API error or an output write failure + */ + public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_FILE_TRIGGERED.getLog()); + LogUtil.printInfoLog(InfoLogs.VALIDATE_DEIDENTIFY_FILE_REQUEST.getLog()); + DetectValidations.validateDeidentifyFileRequest(request); + String token = resolveToken(); + DeidentifyFileRequestV2 apiRequest = DetectRequestMapper.toDeidentifyFileRequest(request, this.vaultConfig.getVaultId()); + String runId; + try { + DeidentifyFileResponseV2 apiResponse = filesClient().deidentifyFileV2(apiRequest, requestOptions(token)); + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_FILE_REQUEST_RESOLVED.getLog()); + runId = apiResponse.getRunId().orElse(null); + } catch (ApiClientApiException e) { + throw toSkyflowException(e, ErrorLogs.DEIDENTIFY_FILE_REQUEST_REJECTED); + } catch (ApiClientException e) { + LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_FILE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e); + } + DeidentifyFileResponse response = DeidentifyFileFlow.complete(request, runId, + id -> getRun(GetRunRequest.builder().runId(id).build())); + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_FILE_SUCCESS.getLog()); + return response; + } + + /** + * Replaces tokens in a file with their original values or a redacted rendering. Synchronous: + * the re-identified file is returned in the response rather than through a run id. + * + * @param request the file (base64, skyflow id or presigned URL) plus optional per-group redaction rules + * @return status, output files and metrics + * @throws SkyflowException on validation failure, credential failure or an API error + */ + public ReidentifyFileResponse reidentifyFile(ReidentifyFileRequest request) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_FILE_TRIGGERED.getLog()); + LogUtil.printInfoLog(InfoLogs.VALIDATE_REIDENTIFY_FILE_REQUEST.getLog()); + ReidentifyFileValidations.validateReidentifyFileRequest(request); + String token = resolveToken(); + ReidentifyFileRequestV2 apiRequest = ReidentifyFileMapper.toApiRequest(request, this.vaultConfig.getVaultId()); + try { + ReidentifyFileResponseV2 apiResponse = filesClient().reidentifyFileV2(apiRequest, requestOptions(token)); + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_FILE_REQUEST_RESOLVED.getLog()); + ReidentifyFileResponse response = ReidentifyFileMapper.toResponse(apiResponse); + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_FILE_SUCCESS.getLog()); + return response; + } catch (ApiClientApiException e) { + throw toSkyflowException(e, ErrorLogs.REIDENTIFY_FILE_REQUEST_REJECTED); + } catch (ApiClientException e) { + LogUtil.printErrorLog(ErrorLogs.REIDENTIFY_FILE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e); + } + } + + /** + * Retrieves the status and, once complete, the outputs of a Detect file run. + * + * @param request the run id returned by {@code deidentifyFile} + * @return status, output files, metrics and failure message + * @throws SkyflowException on validation failure, credential failure or an API error + */ + public GetRunResponse getRun(GetRunRequest request) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GET_RUN_TRIGGERED.getLog()); + LogUtil.printInfoLog(InfoLogs.VALIDATE_GET_RUN_REQUEST.getLog()); + DetectValidations.validateGetRunRequest(request); + String token = resolveToken(); + String runId = request.getRunId().trim(); + GetRunV2Request apiRequest = GetRunV2Request.builder().vaultId(this.vaultConfig.getVaultId()).build(); + try { + DetectRunsResponseV2 apiResponse = filesClient().getRunV2(runId, apiRequest, requestOptions(token)); + LogUtil.printInfoLog(InfoLogs.GET_RUN_REQUEST_RESOLVED.getLog()); + GetRunResponse response = DetectResponseMapper.toGetRunResponse(runId, apiResponse); + LogUtil.printInfoLog(InfoLogs.GET_RUN_SUCCESS.getLog()); + return response; + } catch (ApiClientApiException e) { + throw toSkyflowException(e, ErrorLogs.GET_RUN_REQUEST_REJECTED); + } catch (ApiClientException e) { + LogUtil.printErrorLog(ErrorLogs.GET_RUN_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e); + } + } + + /** + * Screens text for toxicity and denied topics. Synchronous. + * + * @param request text plus the checks to apply + * @return the overall validation result and the individual check outcomes + * @throws SkyflowException on validation failure, credential failure or an API error + */ + public CheckGuardrailsResponse checkGuardrails(CheckGuardrailsRequest request) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.CHECK_GUARDRAILS_TRIGGERED.getLog()); + LogUtil.printInfoLog(InfoLogs.VALIDATE_CHECK_GUARDRAILS_REQUEST.getLog()); + DetectValidations.validateCheckGuardrailsRequest(request); + String token = resolveToken(); + DetectGuardrailsRequestV2 apiRequest = + DetectRequestMapper.toCheckGuardrailsRequest(request, this.vaultConfig.getVaultId()); + try { + DetectGuardrailsResponseV2 apiResponse = guardrailsClient().checkGuardrailsV2(apiRequest, requestOptions(token)); + LogUtil.printInfoLog(InfoLogs.CHECK_GUARDRAILS_REQUEST_RESOLVED.getLog()); + CheckGuardrailsResponse response = DetectResponseMapper.toCheckGuardrailsResponse(apiResponse); + LogUtil.printInfoLog(InfoLogs.CHECK_GUARDRAILS_SUCCESS.getLog()); + return response; + } catch (ApiClientApiException e) { + throw toSkyflowException(e, ErrorLogs.CHECK_GUARDRAILS_REQUEST_REJECTED); + } catch (ApiClientException e) { + LogUtil.printErrorLog(ErrorLogs.CHECK_GUARDRAILS_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e); + } + } + + // ------------------------------------------------------------------ + // Transport plumbing + // ------------------------------------------------------------------ + + /** + * @return client options for the current URL, vault id and HTTP settings, rebuilt when any change + */ + private synchronized ClientOptions clientOptions() throws SkyflowException { + String vaultUrl = resolveVaultUrl(); + String key = clientKey(vaultUrl); + if (clientOptions == null || !key.equals(clientOptionsKey)) { + clientOptions = buildClientOptions(vaultUrl); + clientOptionsKey = key; + stringsClient = null; + filesClient = null; + guardrailsClient = null; + } + return clientOptions; + } + + /** @return the generated strings client for the current settings */ + protected synchronized StringsV2Client stringsClient() throws SkyflowException { + ClientOptions options = clientOptions(); + if (stringsClient == null) { + stringsClient = new StringsV2Client(options); + } + return stringsClient; + } + + /** @return the generated guardrails client for the current settings */ + protected synchronized GuardrailsV2Client guardrailsClient() throws SkyflowException { + ClientOptions options = clientOptions(); + if (guardrailsClient == null) { + guardrailsClient = new GuardrailsV2Client(options); + } + return guardrailsClient; + } + + /** @return the generated files client for the current settings */ + protected synchronized FilesV2Client filesClient() throws SkyflowException { + ClientOptions options = clientOptions(); + if (filesClient == null) { + filesClient = new FilesV2Client(options); + } + return filesClient; + } + + private String clientKey(String vaultUrl) { + return vaultUrl + "|" + this.vaultConfig.getVaultId() + "|" + effectiveTimeoutSeconds() + "|" + + effectiveMaxRetries() + "|" + effectiveInitialRetryDelayMillis() + "|" + effectiveMaxRetryDelayMillis(); + } + + private ClientOptions buildClientOptions(String vaultUrl) { + ClientOptions.Builder builder = ClientOptions.builder().environment(Environment.custom(vaultUrl)); + Integer timeout = effectiveTimeoutSeconds(); + if (timeout != null) { + builder.timeout(timeout); + } + Integer maxRetries = effectiveMaxRetries(); + if (maxRetries != null) { + builder.maxRetries(maxRetries); + } + Long initialDelay = effectiveInitialRetryDelayMillis(); + if (initialDelay != null) { + builder.initialRetryDelayMillis(initialDelay); + } + Long maxDelay = effectiveMaxRetryDelayMillis(); + if (maxDelay != null) { + builder.maxRetryDelayMillis(maxDelay); + } + return builder.build(); + } + + private RequestOptions requestOptions(String token) { + return RequestOptions.builder() + .addHeader(AUTHORIZATION_HEADER, BEARER_PREFIX + token) + .addHeader(BaseConstants.SDK_METRICS_HEADER_KEY, getSdkMetrics()) + .build(); + } + + private static SkyflowException toSkyflowException(ApiClientApiException e, ErrorLogs errorLog) { + LogUtil.printErrorLog(errorLog.getLog()); + return new SkyflowException(e.statusCode(), e, e.headers(), bodyAsString(e.body())); + } + + static String bodyAsString(Object body) { + if (body == null) { + return null; + } + if (body instanceof String) { + return (String) body; + } + try { + return ObjectMappers.JSON_MAPPER.writeValueAsString(body); + } catch (Exception ex) { + return body.toString(); + } + } +} diff --git a/common/src/test/java/com/skyflow/BaseSkyflowTests.java b/common/src/test/java/com/skyflow/BaseSkyflowTests.java index cfd65ad5..45d5278c 100644 --- a/common/src/test/java/com/skyflow/BaseSkyflowTests.java +++ b/common/src/test/java/com/skyflow/BaseSkyflowTests.java @@ -5,7 +5,7 @@ import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import org.junit.Assert; @@ -45,7 +45,7 @@ public void testAddingExistingVaultConfigThrows() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.VaultIdAlreadyInConfigList.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.VaultIdAlreadyInConfigList.getMessage(), e.getMessage()); } } @@ -57,7 +57,7 @@ public void testUpdatingNonExistentVaultConfigInBuilderThrows() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -70,7 +70,7 @@ public void testUpdatingNonExistentVaultConfigInClientThrows() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -81,7 +81,7 @@ public void testRemovingNonExistentVaultConfigInBuilderThrows() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -104,7 +104,7 @@ public void testRemovingVaultConfigWithoutAddingThrows() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -122,7 +122,7 @@ public void testVaultThrowsWhenNoConfigAdded() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -137,7 +137,7 @@ public void testVaultByIdThrowsAfterRemoval() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -163,7 +163,7 @@ public void testAddingInvalidSkyflowCredentialsThrows() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); } } @@ -350,12 +350,12 @@ protected TestSkyflow self() { Object vault() throws SkyflowException { return resolveOrThrow(this.builder.vaultClientsMap, null, - ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, ErrorMessage.VaultIdNotInConfigList); + ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); } Object vault(String vaultId) throws SkyflowException { return resolveOrThrow(this.builder.vaultClientsMap, vaultId, - ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, ErrorMessage.VaultIdNotInConfigList); + ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); } private static class TestSkyflowClientBuilder extends BaseSkyflowClientBuilder { @@ -365,7 +365,7 @@ private static class TestSkyflowClientBuilder extends BaseSkyflowClientBuilder { }; + + private static GetRunResponse success() { + return success(DataSourceType.BASE64); + } + + private static GetRunResponse success(DataSourceType outputType) { + return new GetRunResponse("run-1", DetectRunStatus.SUCCESS, outputType, + Arrays.asList( + new FileOutput(Base64.getEncoder().encodeToString("redacted".getBytes()), + "REDACTED_FILE", FileDataFormat.TXT), + new FileOutput(Base64.getEncoder().encodeToString("[]".getBytes()), + "ENTITIES", FileDataFormat.JSON)), + new Metrics(null, 1, 8, null, null, null), null); + } + + @Test + public void withoutPollOptionsReturnsRunIdAndNeverFetches() throws Exception { + AtomicInteger fetches = new AtomicInteger(); + DeidentifyFileResponse response = DeidentifyFileFlow.complete( + DeidentifyFileRequest.builder().dataSource(DataSourceType.BASE64).value("x").build(), "run-1", + id -> { fetches.incrementAndGet(); return success(); }, NO_SLEEP); + Assert.assertEquals("run-1", response.getRunId()); + Assert.assertNull(response.getStatus()); + Assert.assertTrue(response.getOutput().isEmpty()); + Assert.assertEquals(0, fetches.get()); + } + + @Test + public void missingRunIdSkipsPollingEvenWhenRequested() throws Exception { + AtomicInteger fetches = new AtomicInteger(); + DeidentifyFileResponse response = DeidentifyFileFlow.complete( + DeidentifyFileRequest.builder().dataSource(DataSourceType.BASE64).value("x") + .pollOptions(PollOptions.builder().build()).build(), null, + id -> { fetches.incrementAndGet(); return success(); }, NO_SLEEP); + Assert.assertNull(response.getRunId()); + Assert.assertNull(response.getStatus()); + Assert.assertEquals(0, fetches.get()); + } + + @Test + public void polledRawRequestMergesRunButWritesNothing() throws Exception { + DeidentifyFileResponse response = DeidentifyFileFlow.complete( + DeidentifyFileRequest.builder().dataSource(DataSourceType.SKYFLOW_ID).value("rec") + .pollOptions(PollOptions.builder().build()).outputDirectory(folder.getRoot().getPath()).build(), + "run-1", id -> success(), NO_SLEEP); + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(2, response.getOutput().size()); + Assert.assertEquals(Integer.valueOf(8), response.getMetrics().getCharacterCount()); + Assert.assertEquals(0, folder.getRoot().list().length); + } + + @Test + public void polledFileRequestWritesOutputsOnSuccess() throws Exception { + File input = folder.newFile("notes.txt"); + Files.write(input.toPath(), "hello".getBytes()); + File outDir = folder.newFolder("out"); + + DeidentifyFileResponse response = DeidentifyFileFlow.complete( + DeidentifyFileRequest.builder().file(input).pollOptions(PollOptions.builder().build()) + .outputDirectory(outDir.getPath()).build(), + "run-1", id -> success(), NO_SLEEP); + + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + File written = new File(outDir, "processed-notes.txt"); + Assert.assertTrue(written.isFile()); + Assert.assertEquals("redacted", new String(Files.readAllBytes(written.toPath()))); + File entities = new File(outDir, "processed-entities-notes.json"); + Assert.assertTrue(entities.isFile()); + Assert.assertEquals("[]", new String(Files.readAllBytes(entities.toPath()))); + Assert.assertEquals(2, outDir.list().length); + } + + @Test + public void polledFileRequestWritesNothingForPresignedUrlOutputs() throws Exception { + File input = folder.newFile("notes.txt"); + File outDir = folder.newFolder("out"); + + DeidentifyFileResponse response = DeidentifyFileFlow.complete( + DeidentifyFileRequest.builder().file(input).pollOptions(PollOptions.builder().build()) + .outputDirectory(outDir.getPath()).build(), + "run-1", id -> success(DataSourceType.PRESIGNED_URL), NO_SLEEP); + + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(DataSourceType.PRESIGNED_URL, response.getOutputType()); + Assert.assertEquals(2, response.getOutput().size()); + Assert.assertEquals(0, outDir.list().length); + } + + @Test + public void polledFileRequestWritesNothingWhenRunFailsOrIsPending() throws Exception { + File input = folder.newFile("notes.txt"); + File outDir = folder.newFolder("out"); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(input) + .pollOptions(PollOptions.builder().maxAttempts(1).build()).outputDirectory(outDir.getPath()).build(); + + DeidentifyFileResponse failed = DeidentifyFileFlow.complete(request, "run-1", + id -> new GetRunResponse(id, DetectRunStatus.FAILED, null, Collections.emptyList(), null, "bad input"), NO_SLEEP); + Assert.assertEquals(DetectRunStatus.FAILED, failed.getStatus()); + Assert.assertEquals("bad input", failed.getMessage()); + + DeidentifyFileResponse pending = DeidentifyFileFlow.complete(request, "run-2", + id -> new GetRunResponse(id, DetectRunStatus.IN_PROGRESS, null, Collections.emptyList(), null, null), NO_SLEEP); + Assert.assertEquals("run-2", pending.getRunId()); + Assert.assertEquals(DetectRunStatus.IN_PROGRESS, pending.getStatus()); + Assert.assertEquals(0, outDir.list().length); + } +} diff --git a/common/src/test/java/com/skyflow/detect/internal/DeidentifyFileMapperTests.java b/common/src/test/java/com/skyflow/detect/internal/DeidentifyFileMapperTests.java new file mode 100644 index 00000000..41886c3c --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/internal/DeidentifyFileMapperTests.java @@ -0,0 +1,146 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyFileResponse; +import com.skyflow.detect.Detect; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.Entity; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.DeidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.types.DetectRunsResponseV2; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; +import java.util.Base64; +import java.util.Collections; + +public class DeidentifyFileMapperTests { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private static String wire(DeidentifyFileRequestV2 request) throws Exception { + return ObjectMappers.JSON_MAPPER.writeValueAsString(request); + } + + @Test + public void mapsRawValueRequest() throws Exception { + DeidentifyFileRequestV2 api = DetectRequestMapper.toDeidentifyFileRequest(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.SKYFLOW_ID).value("rec-1").configurationId("cfg-1").build(), "vault-1"); + Assert.assertEquals("SKYFLOW_ID", api.getDataSource().toString()); + Assert.assertEquals("rec-1", api.getValue()); + Assert.assertEquals("cfg-1", api.getConfigurationId().get()); + Assert.assertFalse(api.getDataFormat().isPresent()); + Assert.assertFalse(api.getConfiguration().isPresent()); + String json = wire(api); + Assert.assertTrue(json, json.contains("\"dataSource\":\"SKYFLOW_ID\"")); + Assert.assertTrue(json, json.contains("\"configurationId\":\"cfg-1\"")); + Assert.assertFalse(json, json.contains("dataFormat")); + Assert.assertFalse(json, json.contains("\"configuration\"")); + } + + @Test + public void dataFormatIsSentLowerCase() throws Exception { + DeidentifyFileRequestV2 api = DetectRequestMapper.toDeidentifyFileRequest(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.PRESIGNED_URL).value("https://s3/in").dataFormat(FileDataFormat.PDF).build(), "v"); + Assert.assertTrue(wire(api).contains("\"dataFormat\":\"pdf\"")); + } + + @Test + public void inlineConfigurationGetsVaultId() throws Exception { + DeidentifyFileRequestV2 api = DetectRequestMapper.toDeidentifyFileRequest(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v") + .configuration(DetectConfiguration.builder().detect(Detect.builder().entities(Collections.singletonList( + Entity.builder().entityType(EntityType.NAME).build())).build()).build()) + .build(), "vault-9"); + String json = wire(api); + Assert.assertTrue(json, json.contains("\"vaultId\":\"vault-9\"")); + Assert.assertTrue(json, json.contains("\"entityType\":\"NAME\"")); + } + + @Test + public void fileRequestIsEncodedAndFormatInferred() throws Exception { + File input = folder.newFile("patient-notes.PDF"); + byte[] content = {1, 2, 3, 4, 5}; + Files.write(input.toPath(), content); + + DeidentifyFileRequestV2 api = DetectRequestMapper.toDeidentifyFileRequest( + DeidentifyFileRequest.builder().file(input).build(), "v"); + Assert.assertEquals("BASE64", api.getDataSource().toString()); + Assert.assertEquals(Base64.getEncoder().encodeToString(content), api.getValue()); + Assert.assertEquals("pdf", api.getDataFormat().get().toString()); + + DeidentifyFileRequestV2 explicit = DetectRequestMapper.toDeidentifyFileRequest( + DeidentifyFileRequest.builder().filePath(input.getPath()).dataFormat(FileDataFormat.TXT).build(), "v"); + Assert.assertEquals("txt", explicit.getDataFormat().get().toString()); + } + + @Test + public void localFileIsAlwaysSentAsBase64EvenIfDataSourceWasCleared() throws Exception { + File input = folder.newFile("a.txt"); + Files.write(input.toPath(), new byte[]{1}); + DeidentifyFileRequestV2 api = DetectRequestMapper.toDeidentifyFileRequest( + DeidentifyFileRequest.builder().file(input).dataSource(null).build(), "v"); + Assert.assertEquals("BASE64", api.getDataSource().toString()); + } + + @Test + public void unknownOrMissingExtensionLeavesFormatForTheServer() throws Exception { + for (String name : new String[]{"archive.heic", "README", "trailing."}) { + File input = folder.newFile(name); + Files.write(input.toPath(), new byte[]{9}); + DeidentifyFileRequestV2 api = DetectRequestMapper.toDeidentifyFileRequest( + DeidentifyFileRequest.builder().file(input).build(), "v"); + Assert.assertFalse(name, api.getDataFormat().isPresent()); + } + } + + @Test + public void unreadableFileIsReportedAsEncodeFailure() { + try { + DetectRequestMapper.toDeidentifyFileRequest( + DeidentifyFileRequest.builder().file(new File(folder.getRoot(), "nope.txt")).build(), "v"); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(BaseErrorMessage.FailedToEncodeFile.getMessage(), e.getMessage()); + } + } + + @Test + public void submittedResponseCarriesOnlyRunId() { + DeidentifyFileResponse response = DetectResponseMapper.submittedDeidentifyFileResponse("run-7"); + Assert.assertEquals("run-7", response.getRunId()); + Assert.assertNull(response.getStatus()); + Assert.assertNull(response.getOutputType()); + Assert.assertTrue(response.getOutput().isEmpty()); + Assert.assertNull(response.getMetrics()); + Assert.assertNull(response.getMessage()); + } + + @Test + public void polledResponseMergesRunIdWithRun() throws Exception { + DetectRunsResponseV2 api = ObjectMappers.JSON_MAPPER.readValue( + "{\"status\":\"SUCCESS\",\"outputType\":\"BASE64\",\"output\":[{\"processedFile\":\"UERG\"," + + "\"processedFileType\":\"REDACTED_FILE\",\"processedFileExtension\":\"pdf\"}],\"metrics\":{\"pages\":2}}", + DetectRunsResponseV2.class); + GetRunResponse run = DetectResponseMapper.toGetRunResponse("run-7", api); + DeidentifyFileResponse response = DetectResponseMapper.toDeidentifyFileResponse("run-7", run); + Assert.assertEquals("run-7", response.getRunId()); + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(DataSourceType.BASE64, response.getOutputType()); + Assert.assertEquals("UERG", response.getOutput().get(0).getProcessedFile()); + Assert.assertEquals(FileDataFormat.PDF, response.getOutput().get(0).getProcessedFileExtension()); + Assert.assertEquals(Integer.valueOf(2), response.getMetrics().getPages()); + } +} diff --git a/common/src/test/java/com/skyflow/detect/internal/DeidentifyFileValidationsTests.java b/common/src/test/java/com/skyflow/detect/internal/DeidentifyFileValidationsTests.java new file mode 100644 index 00000000..9f9a3f62 --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/internal/DeidentifyFileValidationsTests.java @@ -0,0 +1,82 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.PollOptions; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; + +public class DeidentifyFileValidationsTests { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private static void assertRejected(DeidentifyFileRequest request, BaseErrorMessage expected) { + try { + DetectValidations.validateDeidentifyFileRequest(request); + Assert.fail("expected SkyflowException: " + expected); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(expected.getMessage(), e.getMessage()); + } + } + + private static DeidentifyFileRequest.DeidentifyFileRequestBuilder raw() { + return DeidentifyFileRequest.builder().dataSource(DataSourceType.BASE64).value("Zm9v"); + } + + @Test + public void rejectsNullRequest() { + assertRejected(null, BaseErrorMessage.DeidentifyFileRequestNull); + } + + @Test + public void rawValueRequiresDataSourceAndValue() throws SkyflowException { + assertRejected(DeidentifyFileRequest.builder().value("x").build(), BaseErrorMessage.InvalidDataSourceInDeidentifyFile); + assertRejected(DeidentifyFileRequest.builder().dataSource(DataSourceType.SKYFLOW_ID).build(), BaseErrorMessage.InvalidValueInDeidentifyFile); + assertRejected(raw().value(" ").build(), BaseErrorMessage.InvalidValueInDeidentifyFile); + DetectValidations.validateDeidentifyFileRequest(raw().build()); + DetectValidations.validateDeidentifyFileRequest(raw().configurationId("cfg").build()); + } + + @Test + public void fileRequestsNeedAnExistingFileAndNoValue() throws Exception { + File existing = folder.newFile("notes.txt"); + Files.write(existing.toPath(), "hello".getBytes("UTF-8")); + DetectValidations.validateDeidentifyFileRequest(DeidentifyFileRequest.builder().file(existing).build()); + DetectValidations.validateDeidentifyFileRequest(DeidentifyFileRequest.builder().filePath(existing.getPath()).build()); + + assertRejected(DeidentifyFileRequest.builder().file(existing).value("Zm9v").build(), BaseErrorMessage.MultipleFileSourcesInDeidentifyFile); + assertRejected(DeidentifyFileRequest.builder().filePath(new File(folder.getRoot(), "missing.txt").getPath()).build(), + BaseErrorMessage.FileNotFoundToDeidentify); + assertRejected(DeidentifyFileRequest.builder().file(folder.getRoot()).build(), BaseErrorMessage.FileNotFoundToDeidentify); + } + + @Test + public void pollOptionsBoundsAreEnforced() throws SkyflowException { + DetectValidations.validateDeidentifyFileRequest(raw().pollOptions(PollOptions.builder().build()).build()); + DetectValidations.validateDeidentifyFileRequest(raw().pollOptions(PollOptions.builder().waitTime(1).maxAttempts(1).build()).build()); + DetectValidations.validateDeidentifyFileRequest(raw().pollOptions(PollOptions.builder().waitTime(300).maxAttempts(23).build()).build()); + for (int bad : new int[]{0, -1, 301}) { + assertRejected(raw().pollOptions(PollOptions.builder().waitTime(bad).build()).build(), BaseErrorMessage.InvalidWaitTimeInPollOptions); + } + for (int bad : new int[]{0, -5, 24}) { + assertRejected(raw().pollOptions(PollOptions.builder().maxAttempts(bad).build()).build(), BaseErrorMessage.InvalidMaxAttemptsInPollOptions); + } + } + + @Test + public void outputDirectoryRequiresPollOptions() throws SkyflowException { + assertRejected(raw().outputDirectory("/tmp/out").build(), BaseErrorMessage.OutputDirectoryWithoutPollOptions); + DetectValidations.validateDeidentifyFileRequest(raw().outputDirectory(" ").build()); + DetectValidations.validateDeidentifyFileRequest(raw().outputDirectory("/tmp/out").pollOptions(PollOptions.builder().build()).build()); + } +} diff --git a/common/src/test/java/com/skyflow/detect/internal/DetectRequestMapperTests.java b/common/src/test/java/com/skyflow/detect/internal/DetectRequestMapperTests.java new file mode 100644 index 00000000..facad0ec --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/internal/DetectRequestMapperTests.java @@ -0,0 +1,161 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.CustomType; +import com.skyflow.detect.DeidentificationType; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.Detect; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.Entity; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.Image; +import com.skyflow.detect.MaskingMethod; +import com.skyflow.detect.Media; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.RedactionType; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.detect.ReturnEntitiesType; +import com.skyflow.detect.ShiftDates; +import com.skyflow.detect.Transformation; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.resources.guardrailsv2.requests.DetectGuardrailsRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.DeidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.resources.stringsv2.requests.ReidentifyStringRequestV2; +import com.skyflow.generated.detect.rest.types.DetectConfigV2; +import com.skyflow.detect.FileMapping; +import com.skyflow.detect.ObjectEntity; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; + +public class DetectRequestMapperTests { + + @Test + public void storedConfigurationSendsOnlyTextAndId() throws Exception { + DeidentifyStringRequestV2 mapped = DetectRequestMapper.toDeidentifyStringRequest( + DeidentifyStringRequest.builder().text("hello").configurationId("cfg-1").build(), "vault-1"); + Assert.assertEquals("hello", mapped.getText()); + Assert.assertEquals("cfg-1", mapped.getConfigurationId().get()); + Assert.assertFalse(mapped.getConfiguration().isPresent()); + String json = ObjectMappers.JSON_MAPPER.writeValueAsString(mapped); + Assert.assertTrue(json, json.contains("\"configurationId\":\"cfg-1\"")); + Assert.assertFalse("no vault id outside a configuration: " + json, json.contains("vaultId")); + Assert.assertFalse(json, json.contains("\"configuration\":")); + } + + @Test + public void inlineConfigurationIsScopedToVaultAndFullyMapped() throws Exception { + DetectConfiguration configuration = DetectConfiguration.builder() + .name("inline") + .detect(Detect.builder() + .entities(Arrays.asList( + Entity.builder().entityType(EntityType.NAME) + .deidentificationType(DeidentificationType.VAULT_TOKEN) + .destination("persons.name").build(), + Entity.builder().entityType(EntityType.DOB) + .deidentificationType(DeidentificationType.ENTITY_UNIQUE_COUNTER) + .transformation(Transformation.builder() + .shiftDates(ShiftDates.builder().minDays(10).maxDays(30).build()).build()) + .build())) + .restrict(Collections.singletonList("[0-9]{3}-[0-9]{2}-[0-9]{4}")) + .skip(Collections.singletonList("Skyflow")) + .customTypes(Collections.singletonList( + CustomType.builder().label("EMPLOYEE_ID").match(Collections.singletonList("EMP-[0-9]{6}")).build())) + .returnEntities(ReturnEntitiesType.ALL) + .build()) + .media(Media.builder().image(Image.builder().maskingMethod(MaskingMethod.BLUR).outputOcrText(true).build()).build()) + .build(); + + DeidentifyStringRequestV2 mapped = DetectRequestMapper.toDeidentifyStringRequest( + DeidentifyStringRequest.builder().text("hello").configuration(configuration).build(), "vault-1"); + + DetectConfigV2 config = mapped.getConfiguration().get(); + Assert.assertEquals("vault-1", config.getVaultId()); + Assert.assertEquals("inline", config.getName().get()); + Assert.assertFalse(mapped.getConfigurationId().isPresent()); + + String json = ObjectMappers.JSON_MAPPER.writeValueAsString(mapped); + Assert.assertEquals("vault id appears once, inside the inline configuration", + 1, json.split("\"vaultId\":\"vault-1\"", -1).length - 1); + for (String expected : new String[]{ + "\"vaultId\":\"vault-1\"", "\"entityType\":\"NAME\"", "\"deidentificationType\":\"VAULT_TOKEN\"", + "\"destination\":\"persons.name\"", "\"minDays\":10", "\"maxDays\":30", + "\"restrict\":[\"[0-9]{3}-[0-9]{2}-[0-9]{4}\"]", "\"skip\":[\"Skyflow\"]", + "\"label\":\"EMPLOYEE_ID\"", "\"returnEntities\":\"ALL\"", "\"maskingMethod\":\"BLUR\"", "\"outputOcrText\":true"}) { + Assert.assertTrue("missing " + expected + " in " + json, json.contains(expected)); + } + Assert.assertFalse("unset fields must be omitted: " + json, json.contains("\"description\"")); + } + + @Test + public void reidentifyStringCarriesVaultIdAndRedactionLevels() throws Exception { + ReidentifyStringRequestV2 mapped = DetectRequestMapper.toReidentifyStringRequest( + ReidentifyStringRequest.builder() + .text("[NAME_1]") + .redactionLevel(Arrays.asList( + RedactionLevel.builder().entityName(EntityType.NAME).redactionType(RedactionType.MASKED).build(), + RedactionLevel.builder().tokenGroupName("group").redactionPattern("pattern").build())) + .build(), "vault-1"); + Assert.assertEquals("vault-1", mapped.getVaultId()); + Assert.assertEquals("[NAME_1]", mapped.getText()); + Assert.assertEquals(2, mapped.getRedactionLevel().get().size()); + String json = ObjectMappers.JSON_MAPPER.writeValueAsString(mapped); + Assert.assertTrue(json, json.contains("\"entityName\":\"NAME\"")); + Assert.assertTrue(json, json.contains("\"redactionType\":\"MASKED\"")); + Assert.assertTrue(json, json.contains("\"tokenGroupName\":\"group\"")); + Assert.assertTrue(json, json.contains("\"redactionPattern\":\"pattern\"")); + } + + @Test + public void reidentifyStringWithoutRedactionLevelsOmitsField() throws Exception { + ReidentifyStringRequestV2 mapped = DetectRequestMapper.toReidentifyStringRequest( + ReidentifyStringRequest.builder().text("[NAME_1]").build(), "vault-1"); + Assert.assertFalse(mapped.getRedactionLevel().isPresent()); + Assert.assertFalse(ObjectMappers.JSON_MAPPER.writeValueAsString(mapped).contains("redactionLevel")); + } + + @Test + public void everyPublicEntityTypeMapsToAGeneratedValue() { + for (EntityType type : EntityType.values()) { + Entity entity = Entity.builder().entityType(type).build(); + Assert.assertEquals(type.name(), DetectRequestMapper.toEntity(entity).getEntityType().get().toString()); + RedactionLevel level = RedactionLevel.builder().entityName(type).redactionType(RedactionType.DEFAULT).build(); + Assert.assertEquals(type.name(), + DetectRequestMapper.toRedactionLevels(Collections.singletonList(level)).get(0).getEntityName().get().toString()); + } + } + + @Test + public void checkGuardrailsCarriesVaultIdAndOnlySetOptions() throws Exception { + DetectGuardrailsRequestV2 full = DetectRequestMapper.toCheckGuardrailsRequest( + CheckGuardrailsRequest.builder().text("t").checkToxicity(false).denyTopics(Collections.singletonList("x")).build(), "vault-1"); + Assert.assertEquals("vault-1", full.getVaultId()); + Assert.assertEquals("t", full.getText()); + Assert.assertEquals(Boolean.FALSE, full.getCheckToxicity().get()); + Assert.assertEquals(Collections.singletonList("x"), full.getDenyTopics().get()); + + DetectGuardrailsRequestV2 minimal = DetectRequestMapper.toCheckGuardrailsRequest( + CheckGuardrailsRequest.builder().text("t").build(), "vault-1"); + Assert.assertFalse(minimal.getCheckToxicity().isPresent()); + Assert.assertFalse(minimal.getDenyTopics().isPresent()); + } + + @Test + public void nullElementsInConfigurationListsAreSkipped() throws Exception { + com.skyflow.generated.detect.rest.types.DetectConfigV2 api = DetectRequestMapper.toDetectConfig( + DetectConfiguration.builder() + .detect(Detect.builder() + .entities(Arrays.asList(null, Entity.builder().entityType(EntityType.NAME).build())) + .objectEntities(Arrays.asList((ObjectEntity) null)) + .customTypes(Arrays.asList(null, CustomType.builder().label("ID").build())) + .build()) + .fileMapping(Arrays.asList(null, FileMapping.builder().source("in").build())) + .build(), "v"); + Assert.assertEquals(1, api.getDetect().get().getEntities().get().size()); + Assert.assertTrue(api.getDetect().get().getObjectEntities().get().isEmpty()); + Assert.assertEquals(1, api.getDetect().get().getCustomTypes().get().size()); + Assert.assertEquals(1, api.getFileMapping().get().size()); + } +} diff --git a/common/src/test/java/com/skyflow/detect/internal/DetectResponseMapperTests.java b/common/src/test/java/com/skyflow/detect/internal/DetectResponseMapperTests.java new file mode 100644 index 00000000..0a4ab894 --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/internal/DetectResponseMapperTests.java @@ -0,0 +1,140 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.CheckGuardrailsResponse; +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DeidentifyStringResponse; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.GuardrailsValidation; +import com.skyflow.detect.DetectedEntity; +import com.skyflow.detect.ReidentifyStringResponse; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.types.DeidentifyStringResponseV2; +import com.skyflow.generated.detect.rest.types.DetectGuardrailsResponseV2; +import com.skyflow.generated.detect.rest.types.DetectRunsResponseV2; +import com.skyflow.generated.detect.rest.types.ReidentifyStringResponseV2; +import org.junit.Assert; +import org.junit.Test; + +public class DetectResponseMapperTests { + + @Test + public void mapsFullDeidentifyStringResponse() throws Exception { + String json = "{\"processedText\":\"My name is [NAME_1].\",\"entities\":[{\"token\":\"NAME_1\",\"value\":\"\"," + + "\"location\":{\"startIndex\":11,\"endIndex\":19,\"startIndexProcessed\":11,\"endIndexProcessed\":19}," + + "\"entityType\":\"NAME\",\"entityScores\":{\"NAME\":0.9152}}]," + + "\"metrics\":{\"size\":0.05,\"wordCount\":4,\"characterCount\":20,\"duration\":0.2}}"; + DeidentifyStringResponseV2 api = ObjectMappers.JSON_MAPPER.readValue(json, DeidentifyStringResponseV2.class); + + DeidentifyStringResponse response = DetectResponseMapper.toDeidentifyStringResponse(api); + Assert.assertEquals("My name is [NAME_1].", response.getProcessedText()); + Assert.assertEquals(1, response.getEntities().size()); + DetectedEntity entity = response.getEntities().get(0); + Assert.assertEquals("NAME_1", entity.getToken()); + Assert.assertEquals("", entity.getValue()); + Assert.assertEquals("NAME", entity.getEntityType()); + Assert.assertEquals(Integer.valueOf(11), entity.getLocation().getStartIndex()); + Assert.assertEquals(Integer.valueOf(19), entity.getLocation().getEndIndexProcessed()); + Assert.assertEquals(0.9152, entity.getEntityScores().get("NAME"), 1e-9); + Assert.assertEquals(Integer.valueOf(4), response.getMetrics().getWordCount()); + Assert.assertEquals(Integer.valueOf(20), response.getMetrics().getCharacterCount()); + Assert.assertEquals(0.05, response.getMetrics().getSize(), 1e-9); + Assert.assertNull(response.getMetrics().getPages()); + } + + @Test + public void emptyResponseYieldsEmptyEntitiesNotNull() throws Exception { + DeidentifyStringResponseV2 api = ObjectMappers.JSON_MAPPER.readValue("{}", DeidentifyStringResponseV2.class); + DeidentifyStringResponse response = DetectResponseMapper.toDeidentifyStringResponse(api); + Assert.assertNull(response.getProcessedText()); + Assert.assertNotNull(response.getEntities()); + Assert.assertTrue(response.getEntities().isEmpty()); + Assert.assertNull(response.getMetrics()); + } + + @Test + public void nullListElementsFromTheApiAreSkipped() throws Exception { + DeidentifyStringResponseV2 strings = ObjectMappers.JSON_MAPPER.readValue( + "{\"entities\":[null,{\"token\":\"NAME_1\"},null]}", DeidentifyStringResponseV2.class); + Assert.assertEquals(1, DetectResponseMapper.toDeidentifyStringResponse(strings).getEntities().size()); + + DetectRunsResponseV2 run = ObjectMappers.JSON_MAPPER.readValue( + "{\"status\":\"SUCCESS\",\"output\":[null,{\"processedFile\":\"x\"}]}", DetectRunsResponseV2.class); + Assert.assertEquals(1, DetectResponseMapper.toGetRunResponse("r", run).getOutput().size()); + } + + @Test + public void guardrailsResponseWithoutValidationMapsToUnknown() throws Exception { + DetectGuardrailsResponseV2 api = ObjectMappers.JSON_MAPPER.readValue("{}", DetectGuardrailsResponseV2.class); + CheckGuardrailsResponse response = DetectResponseMapper.toCheckGuardrailsResponse(api); + Assert.assertNull(response.getText()); + Assert.assertEquals(GuardrailsValidation.UNKNOWN, response.getValidation()); + Assert.assertNull(response.getToxic()); + Assert.assertNull(response.getDeniedTopic()); + } + + @Test + public void entityWithoutScoresGetsEmptyMap() throws Exception { + DeidentifyStringResponseV2 api = ObjectMappers.JSON_MAPPER.readValue( + "{\"entities\":[{\"token\":\"NAME_1\"}]}", DeidentifyStringResponseV2.class); + DetectedEntity entity = DetectResponseMapper.toDeidentifyStringResponse(api).getEntities().get(0); + Assert.assertNotNull(entity.getEntityScores()); + Assert.assertTrue(entity.getEntityScores().isEmpty()); + Assert.assertNull(entity.getLocation()); + } + + @Test + public void mapsReidentifyStringResponse() throws Exception { + ReidentifyStringResponseV2 api = ObjectMappers.JSON_MAPPER.readValue( + "{\"processedText\":\"My name is John Doe.\",\"metrics\":{\"wordCount\":5}}", ReidentifyStringResponseV2.class); + ReidentifyStringResponse response = DetectResponseMapper.toReidentifyStringResponse(api); + Assert.assertEquals("My name is John Doe.", response.getProcessedText()); + Assert.assertEquals(Integer.valueOf(5), response.getMetrics().getWordCount()); + } + + @Test + public void mapsCompletedRun() throws Exception { + DetectRunsResponseV2 api = ObjectMappers.JSON_MAPPER.readValue( + "{\"status\":\"SUCCESS\",\"outputType\":\"PRESIGNED_URL\",\"output\":[{\"processedFile\":\"https://x/y.pdf\"," + + "\"processedFileType\":\"REDACTED_FILE\",\"processedFileExtension\":\"pdf\"}],\"metrics\":{\"pages\":2}}", + DetectRunsResponseV2.class); + GetRunResponse run = DetectResponseMapper.toGetRunResponse("run-1", api); + Assert.assertEquals("run-1", run.getRunId()); + Assert.assertEquals(DetectRunStatus.SUCCESS, run.getStatus()); + Assert.assertEquals(DataSourceType.PRESIGNED_URL, run.getOutputType()); + Assert.assertEquals("https://x/y.pdf", run.getOutput().get(0).getProcessedFile()); + Assert.assertEquals(FileDataFormat.PDF, run.getOutput().get(0).getProcessedFileExtension()); + Assert.assertEquals(Integer.valueOf(2), run.getMetrics().getPages()); + } + + @Test + public void runWithoutStatusIsUnknownAndUnknownWireValuesAreTolerated() throws Exception { + GetRunResponse empty = DetectResponseMapper.toGetRunResponse("r", + ObjectMappers.JSON_MAPPER.readValue("{}", DetectRunsResponseV2.class)); + Assert.assertEquals(DetectRunStatus.UNKNOWN, empty.getStatus()); + Assert.assertTrue(empty.getOutput().isEmpty()); + Assert.assertNull(empty.getOutputType()); + + GetRunResponse odd = DetectResponseMapper.toGetRunResponse("r", ObjectMappers.JSON_MAPPER.readValue( + "{\"status\":\"NEW_STATE\",\"outputType\":\"FTP\",\"output\":[{\"processedFileExtension\":\"heic\"}]}", + DetectRunsResponseV2.class)); + Assert.assertEquals(DetectRunStatus.UNKNOWN, odd.getStatus()); + Assert.assertNull(odd.getOutputType()); + Assert.assertNull(odd.getOutput().get(0).getProcessedFileExtension()); + } + + @Test + public void mapsGuardrailsResponseAndToleratesUnknownValidation() throws Exception { + CheckGuardrailsResponse failed = DetectResponseMapper.toCheckGuardrailsResponse(ObjectMappers.JSON_MAPPER.readValue( + "{\"text\":\"t\",\"validation\":\"FAILED\",\"toxic\":true}", DetectGuardrailsResponseV2.class)); + Assert.assertEquals("t", failed.getText()); + Assert.assertEquals(GuardrailsValidation.FAILED, failed.getValidation()); + Assert.assertEquals(Boolean.TRUE, failed.getToxic()); + Assert.assertNull(failed.getDeniedTopic()); + + CheckGuardrailsResponse odd = DetectResponseMapper.toCheckGuardrailsResponse(ObjectMappers.JSON_MAPPER.readValue( + "{\"text\":\"t\",\"validation\":\"MAYBE\"}", DetectGuardrailsResponseV2.class)); + Assert.assertEquals(GuardrailsValidation.UNKNOWN, odd.getValidation()); + } +} diff --git a/common/src/test/java/com/skyflow/detect/internal/DetectValidationsTests.java b/common/src/test/java/com/skyflow/detect/internal/DetectValidationsTests.java new file mode 100644 index 00000000..dd154096 --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/internal/DetectValidationsTests.java @@ -0,0 +1,138 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.GetRunRequest; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.RedactionType; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; + +public class DetectValidationsTests { + + private static void assertInvalid(SkyflowException e, BaseErrorMessage expected) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(expected.getMessage(), e.getMessage()); + } + + @Test + public void deidentifyStringRejectsNullRequest() { + try { + DetectValidations.validateDeidentifyStringRequest(null); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + assertInvalid(e, BaseErrorMessage.DeidentifyStringRequestNull); + } + } + + @Test + public void deidentifyStringRejectsBlankText() { + try { + DetectValidations.validateDeidentifyStringRequest( + DeidentifyStringRequest.builder().text(" ").configurationId("cfg").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + assertInvalid(e, BaseErrorMessage.InvalidTextInDeidentifyString); + } + } + + @Test + public void deidentifyStringDoesNotConstrainConfigurationSources() throws SkyflowException { + // configurationId and configuration are both optional on the API: none, either or both pass through + DetectValidations.validateDeidentifyStringRequest(DeidentifyStringRequest.builder().text("hello").build()); + DetectValidations.validateDeidentifyStringRequest(DeidentifyStringRequest.builder().text("hello") + .configurationId("cfg").configuration(DetectConfiguration.builder().build()).build()); + DetectValidations.validateDeidentifyStringRequest( + DeidentifyStringRequest.builder().text("hello").configurationId("cfg").build()); + DetectValidations.validateDeidentifyStringRequest( + DeidentifyStringRequest.builder().text("hello") + .configuration(DetectConfiguration.builder().build()).build()); + } + + @Test + public void reidentifyStringRejectsNullAndBlank() { + try { + DetectValidations.validateReidentifyStringRequest(null); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + assertInvalid(e, BaseErrorMessage.ReidentifyStringRequestNull); + } + try { + DetectValidations.validateReidentifyStringRequest(ReidentifyStringRequest.builder().text("").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + assertInvalid(e, BaseErrorMessage.InvalidTextInReidentifyString); + } + } + + @Test + public void reidentifyStringAcceptsValidRedactionLevels() throws SkyflowException { + DetectValidations.validateReidentifyStringRequest(ReidentifyStringRequest.builder() + .text("[NAME_1]") + .redactionLevel(Arrays.asList( + RedactionLevel.builder().entityName(EntityType.NAME).redactionType(RedactionType.MASKED).build(), + RedactionLevel.builder().tokenGroupName("group").redactionPattern("pattern").build())) + .build()); + DetectValidations.validateReidentifyStringRequest(ReidentifyStringRequest.builder().text("[NAME_1]").build()); + } + + @Test + public void reidentifyStringPassesAnyRedactionLevelShapeThrough() throws SkyflowException { + // The API marks every RedactionLevel field optional; the server applies its own rules. + DetectValidations.validateReidentifyStringRequest(ReidentifyStringRequest.builder().text("[NAME_1]") + .redactionLevel(Arrays.asList( + RedactionLevel.builder().build(), + RedactionLevel.builder().tokenGroupName("g").build(), + RedactionLevel.builder().entityName(EntityType.NAME).redactionType(RedactionType.MASKED).redactionPattern("p").build(), + null)) + .build()); + } + + @Test + public void getRunRequiresRunId() throws SkyflowException { + try { + DetectValidations.validateGetRunRequest(null); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + assertInvalid(e, BaseErrorMessage.GetRunRequestNull); + } + try { + DetectValidations.validateGetRunRequest(GetRunRequest.builder().runId(" ").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + assertInvalid(e, BaseErrorMessage.InvalidRunIdInGetRun); + } + DetectValidations.validateGetRunRequest(GetRunRequest.builder().runId("run-1").build()); + } + + @Test + public void checkGuardrailsRequiresOnlyText() throws SkyflowException { + try { + DetectValidations.validateCheckGuardrailsRequest(null); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + assertInvalid(e, BaseErrorMessage.CheckGuardrailsRequestNull); + } + try { + DetectValidations.validateCheckGuardrailsRequest(CheckGuardrailsRequest.builder().build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + assertInvalid(e, BaseErrorMessage.InvalidTextInCheckGuardrails); + } + // denyTopics is optional on the API and its entries are not inspected by the SDK. + DetectValidations.validateCheckGuardrailsRequest( + CheckGuardrailsRequest.builder().text("hi").denyTopics(Arrays.asList("politics", "", null)).build()); + DetectValidations.validateCheckGuardrailsRequest(CheckGuardrailsRequest.builder().text("hi").build()); + DetectValidations.validateCheckGuardrailsRequest( + CheckGuardrailsRequest.builder().text("hi").checkToxicity(true).denyTopics(Collections.singletonList("politics")).build()); + } +} diff --git a/common/src/test/java/com/skyflow/detect/internal/FileOutputWriterTests.java b/common/src/test/java/com/skyflow/detect/internal/FileOutputWriterTests.java new file mode 100644 index 00000000..70297c59 --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/internal/FileOutputWriterTests.java @@ -0,0 +1,274 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.FileOutput; +import com.skyflow.errors.SkyflowException; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.List; + +public class FileOutputWriterTests { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private static String b64(String text) { + return Base64.getEncoder().encodeToString(text.getBytes()); + } + + @Test + public void writesEachOutputWithV1StyleNames() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("%PDF"), "REDACTED_FILE", FileDataFormat.PDF), + new FileOutput(b64("[]"), "ENTITIES", null)), + DataSourceType.BASE64, "invoice.pdf", folder.getRoot().getPath()); + + Assert.assertEquals(2, written.size()); + Assert.assertEquals("processed-invoice.pdf", written.get(0).getName()); + Assert.assertEquals("processed-entities-invoice.json", written.get(1).getName()); + Assert.assertEquals("%PDF", new String(Files.readAllBytes(written.get(0).toPath()))); + Assert.assertEquals("[]", new String(Files.readAllBytes(written.get(1).toPath()))); + Assert.assertEquals(folder.getRoot(), written.get(0).getParentFile()); + } + + @Test + public void entityOutputsCarryTheirTypeInTheName() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("a"), "ENTITIES", FileDataFormat.JSON), + new FileOutput(b64("b"), "OBJECT_ENTITIES", FileDataFormat.JSON)), + DataSourceType.BASE64, "scan.png", folder.getRoot().getPath()); + Assert.assertEquals("processed-entities-scan.json", written.get(0).getName()); + Assert.assertEquals("processed-object-entities-scan.json", written.get(1).getName()); + } + + @Test + public void jsonInputDoesNotCollideWithItsEntitiesOutput() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("{}"), "REDACTED_TEXT", FileDataFormat.JSON), + new FileOutput(b64("[]"), "ENTITIES", FileDataFormat.JSON)), + DataSourceType.BASE64, "data.json", folder.getRoot().getPath()); + Assert.assertEquals("processed-data.json", written.get(0).getName()); + Assert.assertEquals("processed-entities-data.json", written.get(1).getName()); + } + + @Test + public void nameCollisionsGetTheFileTypeInserted() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("a"), "REDACTED_FILE", FileDataFormat.TXT), + new FileOutput(b64("b"), "REDACTED_TEXT", FileDataFormat.TXT)), + DataSourceType.BASE64, "notes.txt", folder.getRoot().getPath()); + Assert.assertEquals("processed-notes.txt", written.get(0).getName()); + Assert.assertEquals("processed-notes.redacted_text.txt", written.get(1).getName()); + } + + @Test + public void createsMissingOutputDirectory() throws Exception { + File nested = new File(folder.getRoot(), "a/b/c"); + List written = FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "REDACTED_TEXT", FileDataFormat.TXT)), + DataSourceType.BASE64, "notes.txt", nested.getPath()); + Assert.assertTrue(nested.isDirectory()); + Assert.assertEquals(new File(nested, "processed-notes.txt"), written.get(0)); + } + + @Test + public void presignedUrlOutputsAreNotWritten() throws Exception { + List written = FileOutputWriter.write( + Collections.singletonList(new FileOutput("https://s3/out", "REDACTED_FILE", FileDataFormat.PDF)), + DataSourceType.PRESIGNED_URL, "invoice.pdf", folder.getRoot().getPath()); + Assert.assertTrue(written.isEmpty()); + Assert.assertEquals(0, folder.getRoot().list().length); + } + + @Test + public void emptyOrNullOutputsWriteNothing() throws Exception { + Assert.assertTrue(FileOutputWriter.write(null, DataSourceType.BASE64, "x.txt", folder.getRoot().getPath()).isEmpty()); + Assert.assertTrue(FileOutputWriter.write(Collections.emptyList(), DataSourceType.BASE64, "x.txt", folder.getRoot().getPath()).isEmpty()); + Assert.assertTrue(FileOutputWriter.write(Collections.singletonList(new FileOutput(null, "ENTITIES", null)), + DataSourceType.BASE64, "x.txt", folder.getRoot().getPath()).isEmpty()); + } + + @Test + public void invalidBase64IsReportedAsWriteFailure() { + try { + FileOutputWriter.write(Collections.singletonList(new FileOutput("not base64!", "REDACTED_FILE", FileDataFormat.TXT)), + DataSourceType.BASE64, "x.txt", folder.getRoot().getPath()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertTrue(e.getMessage(), e.getMessage().contains("processed-x.txt")); + } + } + + // ---- naming branches ------------------------------------------------------------------- + + @Test + public void nullOrEmptyTypeFallsBackToPlainName() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("a"), null, FileDataFormat.PDF), + new FileOutput(b64("b"), "", FileDataFormat.TXT)), + DataSourceType.BASE64, "invoice.pdf", folder.getRoot().getPath()); + Assert.assertEquals("processed-invoice.pdf", written.get(0).getName()); + Assert.assertEquals("processed-invoice.txt", written.get(1).getName()); + } + + @Test + public void nonEntityOutputWithoutExtensionGetsBin() throws Exception { + List written = FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "REDACTED_TRANSCRIPTION", null)), + DataSourceType.BASE64, "call.mp3", folder.getRoot().getPath()); + Assert.assertEquals("processed-call.bin", written.get(0).getName()); + } + + @Test + public void entityOutputHonoursAnExplicitExtension() throws Exception { + List written = FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "ENTITIES", FileDataFormat.TXT)), + DataSourceType.BASE64, "notes.txt", folder.getRoot().getPath()); + Assert.assertEquals("processed-entities-notes.txt", written.get(0).getName()); + } + + @Test + public void entityTypeMatchIsCaseInsensitive() throws Exception { + List written = FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "entities", null)), + DataSourceType.BASE64, "notes.txt", folder.getRoot().getPath()); + Assert.assertEquals("processed-entities-notes.json", written.get(0).getName()); + } + + @Test + public void duplicateEntityOutputsGetTheTypeInsertedOnCollision() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("a"), "ENTITIES", FileDataFormat.JSON), + new FileOutput(b64("b"), "ENTITIES", FileDataFormat.JSON)), + DataSourceType.BASE64, "scan.png", folder.getRoot().getPath()); + Assert.assertEquals("processed-entities-scan.json", written.get(0).getName()); + Assert.assertEquals("processed-entities-scan.entities.json", written.get(1).getName()); + } + + @Test + public void collisionWithoutATypeUsesARunningNumber() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("a"), null, FileDataFormat.TXT), + new FileOutput(b64("b"), null, FileDataFormat.TXT), + new FileOutput(b64("c"), null, FileDataFormat.TXT)), + DataSourceType.BASE64, "notes.txt", folder.getRoot().getPath()); + Assert.assertEquals("processed-notes.txt", written.get(0).getName()); + Assert.assertEquals("processed-notes.1.txt", written.get(1).getName()); + Assert.assertEquals("processed-notes.2.txt", written.get(2).getName()); + } + + @Test + public void inputNamesWithoutAnExtensionOrWithLeadingDotAreKept() throws Exception { + List plain = FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "ENTITIES", null)), + DataSourceType.BASE64, "README", folder.getRoot().getPath()); + Assert.assertEquals("processed-entities-README.json", plain.get(0).getName()); + + List dotted = FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "REDACTED_TEXT", FileDataFormat.TXT)), + DataSourceType.BASE64, ".notes", folder.getRoot().getPath()); + Assert.assertEquals("processed-.notes.txt", dotted.get(0).getName()); + } + + @Test + public void missingInputNameFallsBackToOutput() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("a"), "REDACTED_FILE", FileDataFormat.PDF), + new FileOutput(b64("b"), "ENTITIES", null)), + DataSourceType.BASE64, null, folder.getRoot().getPath()); + Assert.assertEquals("processed-output.pdf", written.get(0).getName()); + Assert.assertEquals("processed-entities-output.json", written.get(1).getName()); + } + + // ---- directory and output-type branches --------------------------------------------------- + + @Test + public void nullOutputTypeWritesNothing() throws Exception { + List written = FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "REDACTED_FILE", FileDataFormat.PDF)), + null, "invoice.pdf", folder.getRoot().getPath()); + Assert.assertTrue(written.isEmpty()); + Assert.assertEquals(0, folder.getRoot().list().length); + } + + @Test + public void nullElementsInTheOutputListAreSkipped() throws Exception { + List written = FileOutputWriter.write(Arrays.asList( + null, + new FileOutput(b64("x"), "REDACTED_TEXT", FileDataFormat.TXT)), + DataSourceType.BASE64, "notes.txt", folder.getRoot().getPath()); + Assert.assertEquals(1, written.size()); + Assert.assertEquals("processed-notes.txt", written.get(0).getName()); + } + + @Test + public void blankOutputDirectoryWritesToTheWorkingDirectory() throws Exception { + File expected = new File("processed-writer-cwd-test.txt"); + try { + List written = FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "REDACTED_TEXT", FileDataFormat.TXT)), + DataSourceType.BASE64, "writer-cwd-test.txt", " "); + Assert.assertEquals(expected, written.get(0)); + Assert.assertNull(written.get(0).getParentFile()); + Assert.assertTrue(expected.isFile()); + } finally { + Files.deleteIfExists(expected.toPath()); + } + } + + @Test + public void outputDirectoryThatIsAFileIsReportedAsWriteFailure() throws Exception { + File notADirectory = folder.newFile("blocker"); + try { + FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("x"), "REDACTED_TEXT", FileDataFormat.TXT)), + DataSourceType.BASE64, "notes.txt", notADirectory.getPath()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertTrue(e.getMessage(), e.getMessage().contains(notADirectory.getPath())); + } + } + + @Test + public void existingFilesAreOverwritten() throws Exception { + File target = new File(folder.getRoot(), "processed-notes.txt"); + Files.write(target.toPath(), "old".getBytes()); + FileOutputWriter.write( + Collections.singletonList(new FileOutput(b64("new"), "REDACTED_TEXT", FileDataFormat.TXT)), + DataSourceType.BASE64, "notes.txt", folder.getRoot().getPath()); + Assert.assertEquals("new", new String(Files.readAllBytes(target.toPath()))); + } + + @Test + public void aLaterFailureLeavesEarlierFilesOnDisk() throws Exception { + try { + FileOutputWriter.write(Arrays.asList( + new FileOutput(b64("ok"), "REDACTED_FILE", FileDataFormat.PDF), + new FileOutput("not base64!", "ENTITIES", null)), + DataSourceType.BASE64, "invoice.pdf", folder.getRoot().getPath()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertTrue(e.getMessage(), e.getMessage().contains("processed-entities-invoice.json")); + } + Assert.assertTrue(new File(folder.getRoot(), "processed-invoice.pdf").isFile()); + Assert.assertFalse(new File(folder.getRoot(), "processed-entities-invoice.json").exists()); + } + + @Test + public void nameHelpers() { + Assert.assertEquals("notes", FileOutputWriter.stripExtension("notes.txt")); + Assert.assertEquals("archive.tar", FileOutputWriter.stripExtension("archive.tar.gz")); + Assert.assertEquals("README", FileOutputWriter.stripExtension("README")); + Assert.assertEquals(".hidden", FileOutputWriter.stripExtension(".hidden")); + Assert.assertEquals("output", FileOutputWriter.stripExtension(null)); + } +} diff --git a/common/src/test/java/com/skyflow/detect/internal/ReidentifyFileMapperTests.java b/common/src/test/java/com/skyflow/detect/internal/ReidentifyFileMapperTests.java new file mode 100644 index 00000000..88da01e4 --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/internal/ReidentifyFileMapperTests.java @@ -0,0 +1,182 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.RedactionType; +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.detect.ReidentifyFileResponse; +import com.skyflow.generated.detect.rest.core.ObjectMappers; +import com.skyflow.generated.detect.rest.resources.filesv2.requests.ReidentifyFileRequestV2; +import com.skyflow.generated.detect.rest.types.ReidentifyFileResponseV2; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; + +/** Request mapping is checked on the serialised wire JSON, response mapping from raw API JSON. */ +public class ReidentifyFileMapperTests { + + private static String wire(ReidentifyFileRequestV2 request) throws Exception { + return ObjectMappers.JSON_MAPPER.writeValueAsString(request); + } + + private static ReidentifyFileResponse fromJson(String json) throws Exception { + return ReidentifyFileMapper.toResponse(ObjectMappers.JSON_MAPPER.readValue(json, ReidentifyFileResponseV2.class)); + } + + // ─── request ────────────────────────────────────────────────────────────── + + @Test + public void mapsRequiredFieldsAndInjectsVaultId() throws Exception { + ReidentifyFileRequestV2 api = ReidentifyFileMapper.toApiRequest(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("W05BTUVfMV0=").build(), "vault-1"); + + Assert.assertEquals("BASE64", api.getDataSource().toString()); + Assert.assertEquals("W05BTUVfMV0=", api.getValue()); + Assert.assertEquals("vault-1", api.getVaultId()); + Assert.assertFalse(api.getDataFormat().isPresent()); + Assert.assertFalse(api.getRedactionLevel().isPresent()); + + String json = wire(api); + Assert.assertTrue(json, json.contains("\"dataSource\":\"BASE64\"")); + Assert.assertTrue(json, json.contains("\"value\":\"W05BTUVfMV0=\"")); + Assert.assertTrue(json, json.contains("\"vaultId\":\"vault-1\"")); + Assert.assertFalse(json, json.contains("dataFormat")); + Assert.assertFalse(json, json.contains("redactionLevel")); + } + + @Test + public void mapsEveryDataSource() throws Exception { + for (DataSourceType source : DataSourceType.values()) { + ReidentifyFileRequestV2 api = ReidentifyFileMapper.toApiRequest(ReidentifyFileRequest.builder() + .dataSource(source).value("x").build(), "v"); + Assert.assertEquals(source.name(), api.getDataSource().toString()); + Assert.assertTrue(wire(api).contains("\"dataSource\":\"" + source.name() + "\"")); + } + } + + @Test + public void dataFormatIsSentAsLowerCaseWireValue() throws Exception { + for (FileDataFormat format : new FileDataFormat[]{FileDataFormat.TXT, FileDataFormat.CSV, FileDataFormat.JSON, + FileDataFormat.JSONL, FileDataFormat.XML, FileDataFormat.DOCX, FileDataFormat.XLSX, FileDataFormat.PPTX}) { + ReidentifyFileRequestV2 api = ReidentifyFileMapper.toApiRequest(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.SKYFLOW_ID).value("rec").dataFormat(format).build(), "v"); + Assert.assertEquals(format.name().toLowerCase(), api.getDataFormat().get().toString()); + Assert.assertTrue(wire(api).contains("\"dataFormat\":\"" + format.name().toLowerCase() + "\"")); + } + } + + @Test + public void mapsFlowvaultAndSkyvaultStyleRedactionLevels() throws Exception { + ReidentifyFileRequestV2 api = ReidentifyFileMapper.toApiRequest(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.PRESIGNED_URL).value("https://s3/presigned") + .redactionLevel(Arrays.asList( + RedactionLevel.builder().tokenGroupName("names").redactionPattern("mask-middle").build(), + RedactionLevel.builder().entityName(EntityType.EMAIL_ADDRESS).redactionType(RedactionType.MASKED).build())) + .build(), "v"); + + Assert.assertEquals(2, api.getRedactionLevel().get().size()); + String json = wire(api); + Assert.assertTrue(json, json.contains("\"tokenGroupName\":\"names\"")); + Assert.assertTrue(json, json.contains("\"redactionPattern\":\"mask-middle\"")); + Assert.assertTrue(json, json.contains("\"entityName\":\"EMAIL_ADDRESS\"")); + Assert.assertTrue(json, json.contains("\"redactionType\":\"MASKED\"")); + // Unset halves of each level must not be serialised as nulls. + Assert.assertFalse(json, json.contains("null")); + } + + @Test + public void emptyRedactionLevelListIsSentAsEmptyArray() throws Exception { + ReidentifyFileRequestV2 api = ReidentifyFileMapper.toApiRequest(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("x").redactionLevel(Collections.emptyList()).build(), "v"); + Assert.assertTrue(api.getRedactionLevel().get().isEmpty()); + Assert.assertTrue(wire(api).contains("\"redactionLevel\":[]")); + } + + // ─── response ───────────────────────────────────────────────────────────── + + @Test + public void mapsFullResponse() throws Exception { + ReidentifyFileResponse response = fromJson("{\"status\":\"SUCCESS\",\"outputType\":\"PRESIGNED_URL\"," + + "\"output\":[{\"processedFile\":\"https://s3/out-1\",\"processedFileType\":\"REIDENTIFIED_FILE\",\"processedFileExtension\":\"docx\"}," + + "{\"processedFile\":\"https://s3/out-2\",\"processedFileType\":\"ENTITIES\",\"processedFileExtension\":\"json\"}]," + + "\"metrics\":{\"size\":12.5,\"wordCount\":120,\"characterCount\":800,\"pages\":2,\"slides\":0,\"duration\":1.25}}"); + + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(DataSourceType.PRESIGNED_URL, response.getOutputType()); + Assert.assertEquals(2, response.getOutput().size()); + FileOutput first = response.getOutput().get(0); + Assert.assertEquals("https://s3/out-1", first.getProcessedFile()); + Assert.assertEquals("REIDENTIFIED_FILE", first.getProcessedFileType()); + Assert.assertEquals(FileDataFormat.DOCX, first.getProcessedFileExtension()); + Assert.assertEquals("ENTITIES", response.getOutput().get(1).getProcessedFileType()); + Assert.assertEquals(FileDataFormat.JSON, response.getOutput().get(1).getProcessedFileExtension()); + Assert.assertEquals(12.5, response.getMetrics().getSize(), 1e-9); + Assert.assertEquals(Integer.valueOf(120), response.getMetrics().getWordCount()); + Assert.assertEquals(Integer.valueOf(800), response.getMetrics().getCharacterCount()); + Assert.assertEquals(Integer.valueOf(2), response.getMetrics().getPages()); + Assert.assertEquals(Integer.valueOf(0), response.getMetrics().getSlides()); + Assert.assertEquals(1.25, response.getMetrics().getDuration(), 1e-9); + } + + @Test + public void mapsEveryKnownStatusAndOutputType() throws Exception { + for (DetectRunStatus status : DetectRunStatus.values()) { + Assert.assertEquals(status, fromJson("{\"status\":\"" + status.name() + "\"}").getStatus()); + } + for (DataSourceType type : DataSourceType.values()) { + Assert.assertEquals(type, fromJson("{\"outputType\":\"" + type.name() + "\"}").getOutputType()); + } + } + + @Test + public void emptyResponseYieldsDefaultsNotNulls() throws Exception { + ReidentifyFileResponse response = fromJson("{}"); + Assert.assertEquals(DetectRunStatus.UNKNOWN, response.getStatus()); + Assert.assertNull(response.getOutputType()); + Assert.assertNotNull(response.getOutput()); + Assert.assertTrue(response.getOutput().isEmpty()); + Assert.assertNull(response.getMetrics()); + } + + @Test + public void unknownWireValuesDegradeGracefully() throws Exception { + ReidentifyFileResponse response = fromJson("{\"status\":\"BRAND_NEW\",\"outputType\":\"FTP\"," + + "\"output\":[{\"processedFile\":\"x\",\"processedFileType\":\"NEW_KIND\",\"processedFileExtension\":\"heic\"}]}"); + Assert.assertEquals(DetectRunStatus.UNKNOWN, response.getStatus()); + Assert.assertNull(response.getOutputType()); + FileOutput output = response.getOutput().get(0); + Assert.assertEquals("x", output.getProcessedFile()); + Assert.assertEquals("NEW_KIND", output.getProcessedFileType()); + Assert.assertNull(output.getProcessedFileExtension()); + } + + @Test + public void nullOutputElementsAreSkipped() throws Exception { + Assert.assertEquals(1, fromJson("{\"output\":[null,{\"processedFile\":\"x\"},null]}").getOutput().size()); + } + + @Test + public void outputWithMissingFieldsMapsToNulls() throws Exception { + FileOutput output = fromJson("{\"output\":[{}]}").getOutput().get(0); + Assert.assertNull(output.getProcessedFile()); + Assert.assertNull(output.getProcessedFileType()); + Assert.assertNull(output.getProcessedFileExtension()); + } + + @Test + public void outputListIsUnmodifiable() throws Exception { + ReidentifyFileResponse response = fromJson("{\"output\":[{\"processedFile\":\"x\"}]}"); + try { + response.getOutput().clear(); + Assert.fail("expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + Assert.assertEquals(1, response.getOutput().size()); + } + } +} diff --git a/common/src/test/java/com/skyflow/detect/internal/ReidentifyFileValidationsTests.java b/common/src/test/java/com/skyflow/detect/internal/ReidentifyFileValidationsTests.java new file mode 100644 index 00000000..d910fa77 --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/internal/ReidentifyFileValidationsTests.java @@ -0,0 +1,85 @@ +package com.skyflow.detect.internal; + +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.RedactionType; +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.SkyflowException; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; + +public class ReidentifyFileValidationsTests { + + private static ReidentifyFileRequest.ReidentifyFileRequestBuilder valid() { + return ReidentifyFileRequest.builder().dataSource(DataSourceType.BASE64).value("Zm9v"); + } + + private static void assertRejected(ReidentifyFileRequest request, BaseErrorMessage expected) { + try { + ReidentifyFileValidations.validateReidentifyFileRequest(request); + Assert.fail("expected SkyflowException: " + expected); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(expected.getMessage(), e.getMessage()); + } + } + + @Test + public void rejectsNullRequest() { + assertRejected(null, BaseErrorMessage.ReidentifyFileRequestNull); + } + + @Test + public void rejectsMissingDataSource() { + assertRejected(ReidentifyFileRequest.builder().value("Zm9v").build(), BaseErrorMessage.InvalidDataSourceInReidentifyFile); + } + + @Test + public void rejectsNullOrBlankValue() { + assertRejected(ReidentifyFileRequest.builder().dataSource(DataSourceType.BASE64).build(), BaseErrorMessage.InvalidValueInReidentifyFile); + assertRejected(valid().value("").build(), BaseErrorMessage.InvalidValueInReidentifyFile); + assertRejected(valid().value(" \t").build(), BaseErrorMessage.InvalidValueInReidentifyFile); + } + + @Test + public void checksFieldsInOrderDataSourceBeforeValue() { + // Both missing: dataSource is reported first. + assertRejected(ReidentifyFileRequest.builder().build(), BaseErrorMessage.InvalidDataSourceInReidentifyFile); + } + + @Test + public void acceptsMinimalAndFullValidRequests() throws SkyflowException { + ReidentifyFileValidations.validateReidentifyFileRequest(valid().build()); + ReidentifyFileValidations.validateReidentifyFileRequest(valid() + .dataSource(DataSourceType.PRESIGNED_URL).value("https://example.com/f") + .redactionLevel(Arrays.asList( + RedactionLevel.builder().tokenGroupName("g").redactionPattern("p").build(), + RedactionLevel.builder().entityName(EntityType.NAME).redactionType(RedactionType.REDACTED).build(), + RedactionLevel.builder().tokenGroupName("g2").redactionType(RedactionType.PLAIN_TEXT).build(), + RedactionLevel.builder().entityName(EntityType.SSN).redactionPattern("p2").build())) + .build()); + } + + @Test + public void nullOrEmptyRedactionLevelListIsAllowed() throws SkyflowException { + ReidentifyFileValidations.validateReidentifyFileRequest(valid().redactionLevel(null).build()); + ReidentifyFileValidations.validateReidentifyFileRequest(valid().redactionLevel(Collections.emptyList()).build()); + } + + @Test + public void anyRedactionLevelShapePassesThrough() throws SkyflowException { + // Every RedactionLevel field is optional on the API; the server applies its own rules. + ReidentifyFileValidations.validateReidentifyFileRequest(valid().redactionLevel(Arrays.asList( + null, + RedactionLevel.builder().build(), + RedactionLevel.builder().tokenGroupName("g").build(), + RedactionLevel.builder().tokenGroupName("g").entityName(EntityType.NAME) + .redactionPattern("p").redactionType(RedactionType.MASKED).build())).build()); + } +} diff --git a/common/src/test/java/com/skyflow/detect/polling/RunPollerTests.java b/common/src/test/java/com/skyflow/detect/polling/RunPollerTests.java new file mode 100644 index 00000000..1030eec6 --- /dev/null +++ b/common/src/test/java/com/skyflow/detect/polling/RunPollerTests.java @@ -0,0 +1,162 @@ +package com.skyflow.detect.polling; + +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.PollOptions; +import com.skyflow.errors.SkyflowException; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +public class RunPollerTests { + + private static GetRunResponse run(DetectRunStatus status) { + return new GetRunResponse("run-1", status, status == DetectRunStatus.SUCCESS ? DataSourceType.BASE64 : null, + Collections.emptyList(), null, status == DetectRunStatus.FAILED ? "boom" : null); + } + + /** Serves a scripted sequence of statuses and records every sleep instead of sleeping. */ + private static final class Script implements RunPoller.RunFetcher, RunPoller.Sleeper { + final Iterator statuses; + final List sleepsMillis = new ArrayList<>(); + int fetches; + + Script(DetectRunStatus... statuses) { + this.statuses = Arrays.asList(statuses).iterator(); + } + + @Override + public GetRunResponse fetch(String runId) { + Assert.assertEquals("run-1", runId); + fetches++; + Assert.assertTrue("fetched more times than scripted", statuses.hasNext()); + return run(statuses.next()); + } + + @Override + public void sleep(long millis) { + sleepsMillis.add(millis); + } + } + + private static PollOptions options(Integer waitTime, Integer maxAttempts) { + return PollOptions.builder().waitTime(waitTime).maxAttempts(maxAttempts).build(); + } + + @Test + public void terminalStatusesStopImmediatelyWithoutSleeping() throws SkyflowException { + for (DetectRunStatus terminal : new DetectRunStatus[]{DetectRunStatus.SUCCESS, DetectRunStatus.FAILED, DetectRunStatus.UNKNOWN}) { + Script script = new Script(terminal); + GetRunResponse result = RunPoller.poll("run-1", options(null, null), script, script); + Assert.assertEquals(terminal, result.getStatus()); + Assert.assertEquals(1, script.fetches); + Assert.assertTrue(script.sleepsMillis.isEmpty()); + } + } + + @Test + public void nonTerminalStatusesKeepPollingWithExponentialBackoff() throws SkyflowException { + Script script = new Script(DetectRunStatus.QUEUED, DetectRunStatus.QUEUED, DetectRunStatus.IN_PROGRESS, + DetectRunStatus.IN_PROGRESS, DetectRunStatus.SUCCESS); + GetRunResponse result = RunPoller.poll("run-1", options(null, null), script, script); + Assert.assertEquals(DetectRunStatus.SUCCESS, result.getStatus()); + Assert.assertEquals(5, script.fetches); + Assert.assertEquals(Arrays.asList(1000L, 2000L, 4000L, 8000L), script.sleepsMillis); + } + + @Test + public void defaultWaitTimeIsSpentExactlyThenRunIdIsReturned() throws SkyflowException { + DetectRunStatus[] forever = new DetectRunStatus[30]; + Arrays.fill(forever, DetectRunStatus.IN_PROGRESS); + Script script = new Script(forever); + GetRunResponse result = RunPoller.poll("run-1", options(null, null), script, script); + Assert.assertEquals(DetectRunStatus.IN_PROGRESS, result.getStatus()); + // 1+2+4+8+16 = 31, then the 32 s step is trimmed to 29 so the total is exactly 60. + Assert.assertEquals(Arrays.asList(1000L, 2000L, 4000L, 8000L, 16000L, 29000L), script.sleepsMillis); + Assert.assertEquals(7, script.fetches); + } + + @Test + public void delayPlateausAt32SecondsForLongWaits() throws SkyflowException { + DetectRunStatus[] forever = new DetectRunStatus[30]; + Arrays.fill(forever, DetectRunStatus.QUEUED); + Script script = new Script(forever); + RunPoller.poll("run-1", options(300, null), script, script); + // 1+2+4+8+16 = 31, then eight 32 s steps reach 287, and the last step is trimmed to 13 so the total is exactly 300. + Assert.assertEquals(Arrays.asList(1000L, 2000L, 4000L, 8000L, 16000L, 32000L, 32000L, 32000L, 32000L, 32000L, + 32000L, 32000L, 32000L, 13000L), script.sleepsMillis); + Assert.assertEquals(15, script.fetches); + } + + @Test + public void maxAttemptsCapsLookupsBeforeWaitTime() throws SkyflowException { + Script script = new Script(DetectRunStatus.IN_PROGRESS, DetectRunStatus.IN_PROGRESS, DetectRunStatus.IN_PROGRESS); + GetRunResponse result = RunPoller.poll("run-1", options(300, 3), script, script); + Assert.assertEquals(DetectRunStatus.IN_PROGRESS, result.getStatus()); + Assert.assertEquals(3, script.fetches); + Assert.assertEquals(Arrays.asList(1000L, 2000L), script.sleepsMillis); + } + + @Test + public void singleAttemptNeverSleeps() throws SkyflowException { + Script script = new Script(DetectRunStatus.QUEUED); + RunPoller.poll("run-1", options(null, 1), script, script); + Assert.assertEquals(1, script.fetches); + Assert.assertTrue(script.sleepsMillis.isEmpty()); + } + + @Test + public void shortWaitTimeTrimsTheFirstSleep() throws SkyflowException { + Script script = new Script(DetectRunStatus.QUEUED, DetectRunStatus.QUEUED); + RunPoller.poll("run-1", options(1, null), script, script); + Assert.assertEquals(Collections.singletonList(1000L), script.sleepsMillis); + Assert.assertEquals(2, script.fetches); + } + + @Test + public void interruptionReturnsLastRunAndRestoresFlag() throws SkyflowException { + Script script = new Script(DetectRunStatus.IN_PROGRESS, DetectRunStatus.SUCCESS); + RunPoller.Sleeper interrupting = millis -> { + throw new InterruptedException(); + }; + try { + GetRunResponse result = RunPoller.poll("run-1", options(null, null), script, interrupting); + Assert.assertEquals(DetectRunStatus.IN_PROGRESS, result.getStatus()); + Assert.assertEquals(1, script.fetches); + Assert.assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); // clear so later tests are unaffected + } + } + + @Test + public void nullRunOrStatusFromFetcherIsTerminalUnknown() throws SkyflowException { + GetRunResponse fromNull = RunPoller.poll("run-1", options(null, null), runId -> null, millis -> { }); + Assert.assertEquals("run-1", fromNull.getRunId()); + Assert.assertEquals(DetectRunStatus.UNKNOWN, fromNull.getStatus()); + Assert.assertTrue(fromNull.getOutput().isEmpty()); + + GetRunResponse fromNullStatus = RunPoller.poll("run-1", options(null, null), + runId -> new GetRunResponse(runId, null, null, Collections.emptyList(), null, null), millis -> { }); + Assert.assertEquals(DetectRunStatus.UNKNOWN, fromNullStatus.getStatus()); + } + + @Test + public void fetchFailurePropagates() { + RunPoller.RunFetcher failing = runId -> { + throw new SkyflowException(404, "run not found"); + }; + try { + RunPoller.poll("run-1", options(null, null), failing, millis -> { }); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(404, e.getHttpCode()); + } + } +} diff --git a/common/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java b/common/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java index 141548f8..9557b48b 100644 --- a/common/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java +++ b/common/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java @@ -3,7 +3,7 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.auth.rest.core.ApiClientException; import com.skyflow.generated.auth.rest.types.V1GetAuthTokenResponse; @@ -102,7 +102,7 @@ public void testEmptyCredentialsFilePath() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - BaseUtils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), ""), e.getMessage() + BaseUtils.parameterizedString(BaseErrorMessage.FileNotFound.getMessage(), ""), e.getMessage() ); } } @@ -117,7 +117,7 @@ public void testInvalidFilePath() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - BaseUtils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), invalidFilePath), + BaseUtils.parameterizedString(BaseErrorMessage.FileNotFound.getMessage(), invalidFilePath), e.getMessage() ); } @@ -133,7 +133,7 @@ public void testInvalidCredentialsFile() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - BaseUtils.parameterizedString(ErrorMessage.FileInvalidJson.getMessage(), invalidJsonFilePath), + BaseUtils.parameterizedString(BaseErrorMessage.FileInvalidJson.getMessage(), invalidJsonFilePath), e.getMessage() ); } @@ -147,7 +147,7 @@ public void testEmptyCredentialsString() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); } } @@ -159,7 +159,7 @@ public void testInvalidCredentialsString() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); } } @@ -174,7 +174,7 @@ public void testNoPrivateKeyInCredentialsForCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.MissingPrivateKey.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.MissingPrivateKey.getMessage(), e.getMessage()); } } @@ -188,7 +188,7 @@ public void testNoClientIDInCredentialsForCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.MissingClientId.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.MissingClientId.getMessage(), e.getMessage()); } } @@ -202,7 +202,7 @@ public void testNoKeyIDInCredentialsForCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.MissingKeyId.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.MissingKeyId.getMessage(), e.getMessage()); } } @@ -216,7 +216,7 @@ public void testNoTokenURIInCredentialsForCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.MissingTokenUri.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.MissingTokenUri.getMessage(), e.getMessage()); } } @@ -230,7 +230,7 @@ public void testInvalidPrivateKeyInCredentialsForCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); } } @@ -243,7 +243,7 @@ public void testInvalidKeySpecInCredentialsForCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); } } @@ -257,7 +257,7 @@ public void testInvalidTokenURIInCredentialsForCredentials() throws SkyflowExcep Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidTokenUri.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.InvalidTokenUri.getMessage(), e.getMessage()); } } @@ -274,7 +274,7 @@ public void testBearerTokenWithNewFormCredentialKeys() { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); // InvalidKeySpec confirms all credential fields were resolved — failure is at RSA parsing, not field lookup Assert.assertEquals( - BaseUtils.parameterizedString(ErrorMessage.InvalidKeySpec.getMessage(), BaseConstants.SDK_PREFIX), + BaseUtils.parameterizedString(BaseErrorMessage.InvalidKeySpec.getMessage(), BaseConstants.SDK_PREFIX), e.getMessage()); } } @@ -371,7 +371,7 @@ public void testExtractAccessTokenMissingThrowsSkyflowException() throws Excepti Assert.assertTrue(e.getCause() instanceof SkyflowException); SkyflowException skyflowException = (SkyflowException) e.getCause(); Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), skyflowException.getHttpCode()); - Assert.assertEquals(ErrorMessage.MissingAccessToken.getMessage(), skyflowException.getMessage()); + Assert.assertEquals(BaseErrorMessage.MissingAccessToken.getMessage(), skyflowException.getMessage()); } } diff --git a/common/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java b/common/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java index dab89e53..790de436 100644 --- a/common/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java +++ b/common/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java @@ -4,7 +4,7 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.utils.BaseConstants; import com.skyflow.utils.BaseUtils; @@ -94,7 +94,7 @@ public void testEmptyCredentialsFilePath() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(BaseUtils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), ""), e.getMessage()); + Assert.assertEquals(BaseUtils.parameterizedString(BaseErrorMessage.FileNotFound.getMessage(), ""), e.getMessage()); } } @@ -108,7 +108,7 @@ public void testInvalidFilePath() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - BaseUtils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), invalidFilePath), + BaseUtils.parameterizedString(BaseErrorMessage.FileNotFound.getMessage(), invalidFilePath), e.getMessage()); } } @@ -123,7 +123,7 @@ public void testInvalidCredentialsFile() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - BaseUtils.parameterizedString(ErrorMessage.FileInvalidJson.getMessage(), invalidJsonFilePath), + BaseUtils.parameterizedString(BaseErrorMessage.FileInvalidJson.getMessage(), invalidJsonFilePath), e.getMessage() ); } @@ -138,7 +138,7 @@ public void testEmptyCredentialsString() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); // InvalidCredentials has no %s1 placeholder, so no extra arg is passed here. - Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e); } @@ -153,7 +153,7 @@ public void testInvalidCredentialsString() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); // CredentialsStringInvalidJson has no %s1 placeholder, so no extra arg is passed here. - Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); } } @@ -167,7 +167,7 @@ public void testNoPrivateKeyInCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.MissingPrivateKey.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.MissingPrivateKey.getMessage(), e.getMessage()); } } @@ -181,7 +181,7 @@ public void testNoClientIDInCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.MissingClientId.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.MissingClientId.getMessage(), e.getMessage()); } } @@ -195,7 +195,7 @@ public void testNoKeyIDInCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.MissingKeyId.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.MissingKeyId.getMessage(), e.getMessage()); } } @@ -209,7 +209,7 @@ public void testInvalidPrivateKeyInCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); } } @@ -225,7 +225,7 @@ public void testInvalidKeySpecInCredentials() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); } } @@ -245,7 +245,7 @@ public void testSignedDataTokensWithNewFormCredentialKeys() { } catch (SkyflowException e) { // Failure at RSA key parsing (not field lookup) confirms new-form keys clientId/keyId were found Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); } } diff --git a/common/src/test/java/com/skyflow/utils/BaseUtilsTests.java b/common/src/test/java/com/skyflow/utils/BaseUtilsTests.java index bc1bd216..257e9d9b 100644 --- a/common/src/test/java/com/skyflow/utils/BaseUtilsTests.java +++ b/common/src/test/java/com/skyflow/utils/BaseUtilsTests.java @@ -4,7 +4,7 @@ import com.skyflow.config.Credentials; import com.skyflow.enums.Env; import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import org.junit.Assert; import org.junit.BeforeClass; @@ -105,7 +105,7 @@ public void testGenerateBearerTokenWithCredentialsFile() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - BaseUtils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), filePath), + BaseUtils.parameterizedString(BaseErrorMessage.FileNotFound.getMessage(), filePath), e.getMessage() ); } @@ -122,7 +122,7 @@ public void testGenerateBearerTokenWithCredentialsString() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); } } @@ -166,7 +166,7 @@ public void testGenerateBearerTokenWithCredentialsFileAndMapContext() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - BaseUtils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), filePath), + BaseUtils.parameterizedString(BaseErrorMessage.FileNotFound.getMessage(), filePath), e.getMessage() ); } @@ -187,7 +187,7 @@ public void testGenerateBearerTokenWithCredentialsStringAndMapContext() { Assert.fail("Map context should not cause a ClassCastException"); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); } } @@ -205,7 +205,7 @@ public void testGenerateBearerTokenWithContextNeitherStringNorMap() { Assert.fail("Non String/Map context should not cause a ClassCastException"); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); } } @@ -216,7 +216,7 @@ public void testGetPrivateKeyFromPemWithMissingHeader() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); } } @@ -230,7 +230,7 @@ public void testGetPrivateKeyFromPemWithInvalidBase64Body() { Assert.fail("Invalid base64 content should be wrapped into a SkyflowException, not thrown raw"); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); } } diff --git a/common/src/test/java/com/skyflow/vault/controller/BaseDetectControllerTests.java b/common/src/test/java/com/skyflow/vault/controller/BaseDetectControllerTests.java new file mode 100644 index 00000000..4b267bb3 --- /dev/null +++ b/common/src/test/java/com/skyflow/vault/controller/BaseDetectControllerTests.java @@ -0,0 +1,385 @@ +package com.skyflow.vault.controller; + +import com.skyflow.config.BaseVaultConfig; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.DeidentifyStringResponse; +import com.skyflow.detect.Detect; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.Entity; +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.CheckGuardrailsResponse; +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.GetRunRequest; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.GuardrailsValidation; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.detect.ReidentifyStringResponse; +import com.skyflow.enums.Env; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicInteger; + +public class BaseDetectControllerTests { + + /** Minimal SDK controller: fixed URL, counted tokens, no credential chain. */ + private static final class TestDetectController extends BaseDetectController { + private String vaultUrl; + private final AtomicInteger tokenCalls = new AtomicInteger(); + private SkyflowException tokenFailure; + + TestDetectController(BaseVaultConfig config, String vaultUrl) { + super(config, null); + this.vaultUrl = vaultUrl; + } + + @Override + protected String resolveVaultUrl() { + return vaultUrl; + } + + @Override + protected String getSdkMetrics() { + return "{\"sdk_name_version\":\"test\"}"; + } + + @Override + protected String resolveToken() throws SkyflowException { + if (tokenFailure != null) { + throw tokenFailure; + } + return "token-" + tokenCalls.incrementAndGet(); + } + } + + private MockWebServer server; + private TestDetectController controller; + + private static BaseVaultConfig config(String vaultId) { + BaseVaultConfig config = new BaseVaultConfig(); + config.setVaultId(vaultId); + config.setClusterId("cluster"); + config.setEnv(Env.PROD); + return config; + } + + @Before + public void setUp() throws Exception { + server = new MockWebServer(); + server.start(); + controller = new TestDetectController(config("vault-1"), server.url("").toString()); + controller.setCommonHttpConfig(null, 0, null, null); + } + + @After + public void tearDown() throws Exception { + server.shutdown(); + } + + @Test + public void deidentifyStringSendsScopedRequestAndMapsResponse() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") + .setBody("{\"processedText\":\"My name is [NAME_1].\",\"entities\":[{\"token\":\"NAME_1\",\"entityType\":\"NAME\"," + + "\"location\":{\"startIndex\":11,\"endIndex\":19}}],\"metrics\":{\"wordCount\":4}}")); + + DeidentifyStringResponse response = controller.deidentifyString(DeidentifyStringRequest.builder() + .text("My name is John Doe.") + .configuration(DetectConfiguration.builder() + .detect(Detect.builder().entities(Collections.singletonList( + Entity.builder().entityType(EntityType.NAME).build())).build()) + .build()) + .build()); + + Assert.assertEquals("My name is [NAME_1].", response.getProcessedText()); + Assert.assertEquals("NAME_1", response.getEntities().get(0).getToken()); + Assert.assertEquals(Integer.valueOf(4), response.getMetrics().getWordCount()); + + RecordedRequest recorded = server.takeRequest(); + Assert.assertEquals("POST", recorded.getMethod()); + Assert.assertEquals("/v2/detect/deidentify/string", recorded.getPath()); + Assert.assertEquals("Bearer token-1", recorded.getHeader("Authorization")); + Assert.assertEquals("{\"sdk_name_version\":\"test\"}", recorded.getHeader("sky-metadata")); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"text\":\"My name is John Doe.\"")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(body, body.contains("\"entityType\":\"NAME\"")); + Assert.assertFalse(body, body.contains("configurationId")); + } + + @Test + public void reidentifyStringSendsVaultIdInBodyAndRefreshesTokenPerCall() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"processedText\":\"My name is John Doe.\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"processedText\":\"My name is J**n D*e.\"}")); + + ReidentifyStringResponse first = controller.reidentifyString( + ReidentifyStringRequest.builder().text("My name is [NAME_1].").build()); + ReidentifyStringResponse second = controller.reidentifyString(ReidentifyStringRequest.builder() + .text("My name is [NAME_1].") + .redactionLevel(Collections.singletonList( + RedactionLevel.builder().tokenGroupName("group").redactionPattern("mask").build())) + .build()); + + Assert.assertEquals("My name is John Doe.", first.getProcessedText()); + Assert.assertEquals("My name is J**n D*e.", second.getProcessedText()); + + RecordedRequest r1 = server.takeRequest(); + Assert.assertEquals("/v2/detect/reidentify/string", r1.getPath()); + Assert.assertEquals("Bearer token-1", r1.getHeader("Authorization")); + String body1 = r1.getBody().readUtf8(); + Assert.assertTrue(body1, body1.contains("\"vaultId\":\"vault-1\"")); + Assert.assertFalse(body1, body1.contains("redactionLevel")); + + RecordedRequest r2 = server.takeRequest(); + Assert.assertEquals("Bearer token-2", r2.getHeader("Authorization")); + String body2 = r2.getBody().readUtf8(); + Assert.assertTrue(body2, body2.contains("\"tokenGroupName\":\"group\"")); + Assert.assertTrue(body2, body2.contains("\"redactionPattern\":\"mask\"")); + } + + @Test + public void getRunQueriesRunByIdScopedToVault() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setBody( + "{\"status\":\"SUCCESS\",\"outputType\":\"BASE64\",\"output\":[{\"processedFile\":\"QUJD\"," + + "\"processedFileType\":\"REDACTED_FILE\",\"processedFileExtension\":\"pdf\"}," + + "{\"processedFile\":\"e30=\",\"processedFileType\":\"ENTITIES\",\"processedFileExtension\":\"json\"}]," + + "\"metrics\":{\"pages\":3,\"size\":12.5}}")); + + GetRunResponse response = controller.getRun(GetRunRequest.builder().runId(" run-42 ").build()); + + Assert.assertEquals("run-42", response.getRunId()); + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(DataSourceType.BASE64, response.getOutputType()); + Assert.assertEquals(2, response.getOutput().size()); + Assert.assertEquals("QUJD", response.getOutput().get(0).getProcessedFile()); + Assert.assertEquals("REDACTED_FILE", response.getOutput().get(0).getProcessedFileType()); + Assert.assertEquals(FileDataFormat.PDF, response.getOutput().get(0).getProcessedFileExtension()); + Assert.assertEquals(FileDataFormat.JSON, response.getOutput().get(1).getProcessedFileExtension()); + Assert.assertEquals(Integer.valueOf(3), response.getMetrics().getPages()); + Assert.assertNull(response.getMessage()); + + RecordedRequest recorded = server.takeRequest(); + Assert.assertEquals("GET", recorded.getMethod()); + Assert.assertEquals("/v2/detect/runs/run-42?vaultId=vault-1", recorded.getPath()); + Assert.assertEquals("Bearer token-1", recorded.getHeader("Authorization")); + Assert.assertEquals("{\"sdk_name_version\":\"test\"}", recorded.getHeader("sky-metadata")); + } + + @Test + public void getRunReportsPendingAndFailedRuns() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"IN_PROGRESS\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody( + "{\"status\":\"FAILED\",\"message\":\"unsupported file\",\"output\":[]}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"SOMETHING_NEW\"}")); + + GetRunResponse pending = controller.getRun(GetRunRequest.builder().runId("r1").build()); + Assert.assertEquals(DetectRunStatus.IN_PROGRESS, pending.getStatus()); + Assert.assertNotNull(pending.getOutput()); + Assert.assertTrue(pending.getOutput().isEmpty()); + Assert.assertNull(pending.getOutputType()); + Assert.assertNull(pending.getMetrics()); + + GetRunResponse failed = controller.getRun(GetRunRequest.builder().runId("r2").build()); + Assert.assertEquals(DetectRunStatus.FAILED, failed.getStatus()); + Assert.assertEquals("unsupported file", failed.getMessage()); + + GetRunResponse unknown = controller.getRun(GetRunRequest.builder().runId("r3").build()); + Assert.assertEquals("unrecognised statuses degrade to UNKNOWN", DetectRunStatus.UNKNOWN, unknown.getStatus()); + } + + @Test + public void getRunValidatesRunIdBeforeTokenOrNetwork() throws Exception { + for (GetRunRequest bad : new GetRunRequest[]{null, GetRunRequest.builder().build(), GetRunRequest.builder().runId(" ").build()}) { + try { + controller.getRun(bad); + Assert.fail("expected SkyflowException for " + bad); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + Assert.assertEquals(0, controller.tokenCalls.get()); + Assert.assertEquals(0, server.getRequestCount()); + } + + @Test + public void getRunMapsNotFound() throws Exception { + server.enqueue(new MockResponse().setResponseCode(404) + .setBody("{\"error\":{\"grpc_code\":5,\"http_code\":404,\"message\":\"run not found\",\"http_status\":\"Not Found\",\"details\":[]}}")); + try { + controller.getRun(GetRunRequest.builder().runId("missing").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(404, e.getHttpCode()); + Assert.assertEquals("run not found", e.getMessage()); + } + } + + @Test + public void checkGuardrailsSendsScopedRequestAndMapsResponse() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setBody( + "{\"text\":\"tell me about politics\",\"validation\":\"FAILED\",\"toxic\":false,\"deniedTopic\":true}")); + + CheckGuardrailsResponse response = controller.checkGuardrails(CheckGuardrailsRequest.builder() + .text("tell me about politics") + .checkToxicity(true) + .denyTopics(Arrays.asList("politics", "medical advice")) + .build()); + + Assert.assertEquals("tell me about politics", response.getText()); + Assert.assertEquals(GuardrailsValidation.FAILED, response.getValidation()); + Assert.assertEquals(Boolean.FALSE, response.getToxic()); + Assert.assertEquals(Boolean.TRUE, response.getDeniedTopic()); + + RecordedRequest recorded = server.takeRequest(); + Assert.assertEquals("POST", recorded.getMethod()); + Assert.assertEquals("/v2/detect/guardrails", recorded.getPath()); + Assert.assertEquals("Bearer token-1", recorded.getHeader("Authorization")); + Assert.assertEquals("{\"sdk_name_version\":\"test\"}", recorded.getHeader("sky-metadata")); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"text\":\"tell me about politics\"")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(body, body.contains("\"checkToxicity\":true")); + Assert.assertTrue(body, body.contains("\"denyTopics\":[\"politics\",\"medical advice\"]")); + } + + @Test + public void checkGuardrailsOmitsUnsetOptionsAndMapsPassed() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"text\":\"hello\",\"validation\":\"PASSED\"}")); + CheckGuardrailsResponse response = controller.checkGuardrails(CheckGuardrailsRequest.builder().text("hello").build()); + Assert.assertEquals(GuardrailsValidation.PASSED, response.getValidation()); + Assert.assertNull(response.getToxic()); + Assert.assertNull(response.getDeniedTopic()); + String body = server.takeRequest().getBody().readUtf8(); + Assert.assertFalse(body, body.contains("checkToxicity")); + Assert.assertFalse(body, body.contains("denyTopics")); + } + + @Test + public void checkGuardrailsValidatesBeforeTokenOrNetwork() throws Exception { + CheckGuardrailsRequest[] bad = { + null, + CheckGuardrailsRequest.builder().text(" ").build(), + }; + for (CheckGuardrailsRequest request : bad) { + try { + controller.checkGuardrails(request); + Assert.fail("expected SkyflowException for " + request); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + Assert.assertEquals(0, controller.tokenCalls.get()); + Assert.assertEquals(0, server.getRequestCount()); + } + + @Test + public void deidentifyStringWithStoredConfigurationSendsOnlyTextAndId() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"processedText\":\"[NAME_1]\"}")); + controller.deidentifyString(DeidentifyStringRequest.builder().text("John").configurationId("cfg-1").build()); + String body = server.takeRequest().getBody().readUtf8(); + Assert.assertEquals("{\"text\":\"John\",\"configurationId\":\"cfg-1\"}", body); + } + + @Test + public void apiErrorIsMappedToSkyflowExceptionWithServerMessage() throws Exception { + server.enqueue(new MockResponse().setResponseCode(400).setHeader("x-request-id", "req-123") + .setBody("{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"configuration not found\"," + + "\"http_status\":\"Bad Request\",\"details\":[]}}")); + try { + controller.deidentifyString(DeidentifyStringRequest.builder().text("hello").configurationId("missing").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(400, e.getHttpCode()); + Assert.assertEquals("configuration not found", e.getMessage()); + Assert.assertEquals("req-123", e.getRequestId()); + Assert.assertEquals(Integer.valueOf(3), e.getGrpcCode()); + } + } + + @Test + public void unmodelledStatusIsStillMapped() throws Exception { + server.enqueue(new MockResponse().setResponseCode(404) + .setBody("{\"error\":{\"grpc_code\":5,\"http_code\":404,\"message\":\"not found\",\"http_status\":\"Not Found\",\"details\":[]}}")); + try { + controller.reidentifyString(ReidentifyStringRequest.builder().text("[NAME_1]").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(404, e.getHttpCode()); + Assert.assertEquals("not found", e.getMessage()); + } + } + + @Test + public void validationFailsBeforeTokenOrNetwork() throws Exception { + try { + controller.deidentifyString(DeidentifyStringRequest.builder().text(" ").configurationId("cfg").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.InvalidTextInDeidentifyString.getMessage(), e.getMessage()); + } + Assert.assertEquals(0, controller.tokenCalls.get()); + Assert.assertEquals(0, server.getRequestCount()); + } + + @Test + public void tokenFailurePropagatesWithoutNetworkCall() throws Exception { + controller.tokenFailure = new SkyflowException(401, "no credentials"); + try { + controller.reidentifyString(ReidentifyStringRequest.builder().text("[NAME_1]").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals("no credentials", e.getMessage()); + } + Assert.assertEquals(0, server.getRequestCount()); + } + + @Test + public void clientIsRebuiltWhenUrlOrHttpConfigChanges() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{}")); + controller.reidentifyString(ReidentifyStringRequest.builder().text("[NAME_1]").build()); + Object first = controller.stringsClient(); + Assert.assertSame("same settings must reuse the client", first, controller.stringsClient()); + + controller.setCommonHttpConfig(30, 0, null, null); + Object afterConfig = controller.stringsClient(); + Assert.assertNotSame("changed http config must rebuild", first, afterConfig); + + MockWebServer other = new MockWebServer(); + other.start(); + try { + controller.vaultUrl = other.url("").toString(); + other.enqueue(new MockResponse().setResponseCode(200).setBody("{\"processedText\":\"moved\"}")); + Assert.assertEquals("moved", controller.reidentifyString( + ReidentifyStringRequest.builder().text("[NAME_1]").build()).getProcessedText()); + Assert.assertNotSame("changed url must rebuild", afterConfig, controller.stringsClient()); + Assert.assertEquals(1, other.getRequestCount()); + } finally { + other.shutdown(); + } + } + + @Test + public void setVaultConfigRescopesRequests() throws Exception { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{}")); + controller.reidentifyString(ReidentifyStringRequest.builder().text("[NAME_1]").build()); + controller.setVaultConfig(config("vault-2")); + controller.reidentifyString(ReidentifyStringRequest.builder().text("[NAME_1]").build()); + Assert.assertTrue(server.takeRequest().getBody().readUtf8().contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(server.takeRequest().getBody().readUtf8().contains("\"vaultId\":\"vault-2\"")); + } +} diff --git a/docs/api_reference.md b/docs/api_reference.md index 8f5716a5..5908751c 100644 --- a/docs/api_reference.md +++ b/docs/api_reference.md @@ -204,60 +204,69 @@ Parameters listed with their defaults as defined in the builders. |----------------|---------|-------------| | `values(List)` | _(required)_ | List of [`ColumnValue`](#columnvalue) objects to tokenize. | -### `DeidentifyTextRequest` +### `DeidentifyStringRequest` -`com.skyflow.vault.detect` — passed to `detect().deidentifyText()`. +`com.skyflow.detect` — passed to `detect().deidentifyString()`. | Builder method | Default | Description | |----------------|---------|-------------| | `text(String)` | _(required)_ | Text to de-identify. | -| `entities(List)` | `null` | Entity types to detect. See [`DetectEntities`](#detectentities). | -| `allowRegexList(List)` | `null` | Regex patterns to always treat as detectable. | -| `restrictRegexList(List)` | `null` | Regex patterns to exclude from detection. | -| `tokenFormat(TokenFormat)` | `null` | Token format controlling token types per entity. See [`TokenFormat`](#tokenformat). | -| `transformations(Transformations)` | `null` | Data transformations (e.g. date shifting). See [`Transformations`](#transformations). | +| `configurationId(String)` | `null` | Id of a Detect configuration created in Studio or through the management API. | +| `configuration(DetectConfiguration)` | `null` | Inline configuration. See [`DetectConfiguration`](#detectconfiguration). Supply this or `configurationId`. | -### `ReidentifyTextRequest` +### `DeidentifyFileRequest` -`com.skyflow.vault.detect` — passed to `detect().reidentifyText()`. +`com.skyflow.detect` — passed to `detect().deidentifyFile()`. Supply the file through exactly one of `value` (with a `dataSource`), `file` or `filePath`. | Builder method | Default | Description | |----------------|---------|-------------| -| `text(String)` | _(required)_ | The redacted/de-identified text to re-identify. | -| `redactedEntities(List)` | `null` | Entity types to keep redacted. | -| `maskedEntities(List)` | `null` | Entity types to mask. | -| `plainTextEntities(List)` | `null` | Entity types to reveal as plain text. | +| `dataSource(DataSourceType)` | `null` | How `value` supplies the file. See [`DataSourceType`](#datasourcetype). | +| `value(String)` | `null` | Base64 content, a skyflow id, or a presigned URL, per `dataSource`. | +| `file(File)` | `null` | Local file; read and base64-encoded when sent, `dataSource` set to `BASE64`. | +| `filePath(String)` | `null` | Same as `file(File)`, from a path. | +| `dataFormat(FileDataFormat)` | inferred from the extension | File format. See [`FileDataFormat`](#filedataformat). | +| `configurationId(String)` | `null` | Id of a stored Detect configuration. | +| `configuration(DetectConfiguration)` | `null` | Inline configuration. See [`DetectConfiguration`](#detectconfiguration). | +| `pollOptions(PollOptions)` | `null` | Poll the run after submitting. `null` submits only and returns the run id. See [`PollOptions`](#polloptions). | +| `outputDirectory(String)` | working directory | Where outputs are written on success. Requires `pollOptions` and a local file. | -### `DeidentifyFileRequest` +### `ReidentifyStringRequest` + +`com.skyflow.detect` — passed to `detect().reidentifyString()`. + +| Builder method | Default | Description | +|----------------|---------|-------------| +| `text(String)` | _(required)_ | The de-identified text to re-identify. | +| `redactionLevel(List)` | `null` | Per-entity redaction rules. See [`RedactionLevel`](#redactionlevel). Without rules every token is replaced by its original value. | + +### `ReidentifyFileRequest` -`com.skyflow.vault.detect` — passed to `detect().deidentifyFile()`. +`com.skyflow.detect` — passed to `detect().reidentifyFile()`. Synchronous: the re-identified file comes back in the response. | Builder method | Default | Description | |----------------|---------|-------------| -| `file(FileInput)` | _(required)_ | File source. See [`FileInput`](#fileinput). | -| `entities(List)` | `null` | Entity types to detect. | -| `allowRegexList(List)` | `null` | Regex patterns to always treat as detectable. | -| `restrictRegexList(List)` | `null` | Regex patterns to exclude. | -| `tokenFormat(TokenFormat)` | `null` | Token format per entity. | -| `transformations(Transformations)` | `null` | Transformations (not supported for Documents/Images/PDFs). | -| `outputProcessedImage(Boolean)` | `false` | Include the processed image in the response. | -| `outputOcrText(Boolean)` | `false` | Include OCR text in the response. | -| `maskingMethod(MaskingMethod)` | `null` | See [`MaskingMethod`](#maskingmethod). | -| `pixelDensity(Number)` | `null` | Pixel density for PDF processing. | -| `maxResolution(Number)` | `null` | Max resolution for PDF processing. | -| `outputProcessedAudio(Boolean)` | `false` | Include processed audio in the response. | -| `outputTranscription(DetectOutputTranscriptions)` | `null` | See [`DetectOutputTranscriptions`](#detectoutputtranscriptions). | -| `bleep(AudioBleep)` | `null` | Audio bleep configuration. See [`AudioBleep`](#audiobleep). | -| `outputDirectory(String)` | `null` | Directory to write the processed file. | -| `waitTime(Integer)` | `null` | Max seconds to wait for async file processing (≤ 64). | - -### `GetDetectRunRequest` - -`com.skyflow.vault.detect` — passed to `detect().getDetectRun()`. +| `dataSource(DataSourceType)` | _(required)_ | `BASE64`, `SKYFLOW_ID` or `PRESIGNED_URL`. | +| `value(String)` | _(required)_ | Base64 content, a skyflow id, or a presigned URL, per `dataSource`. | +| `dataFormat(FileDataFormat)` | `null` | File format. | +| `redactionLevel(List)` | `null` | Per-entity redaction rules. See [`RedactionLevel`](#redactionlevel). | + +### `GetRunRequest` + +`com.skyflow.detect` — passed to `detect().getRun()`. | Builder method | Default | Description | |----------------|---------|-------------| -| `runId(String)` | _(required)_ | The `run_id` returned by a prior `deidentifyFile` call. | +| `runId(String)` | _(required)_ | The run id returned by a prior `deidentifyFile` call. | + +### `CheckGuardrailsRequest` + +`com.skyflow.detect` — passed to `detect().checkGuardrails()`. + +| Builder method | Default | Description | +|----------------|---------|-------------| +| `text(String)` | _(required)_ | Text to screen. | +| `checkToxicity(Boolean)` | `true` on the server | Whether to check for toxicity. | +| `denyTopics(List)` | `null` | Topics to deny. | ### `InvokeConnectionRequest` @@ -363,44 +372,63 @@ Each element returned by `getDetokenizedFields()` and `getErrors()`. |--------|-------------|-------------| | `getTokens()` | `List` | One token per input `ColumnValue`, in order. | -### `DeidentifyTextResponse` +### `DeidentifyStringResponse` -`com.skyflow.vault.detect` — returned by `detect().deidentifyText()`. +`com.skyflow.detect` — returned by `detect().deidentifyString()`. | Getter | Return type | Description | |--------|-------------|-------------| | `getProcessedText()` | `String` | The de-identified text with entity values replaced by tokens. | -| `getEntities()` | `List` | Detected entities. See [`EntityInfo`](#entityinfo). | -| `getWordCount()` | `int` | Word count of the input text. | -| `getCharCount()` | `int` | Character count of the input text. | +| `getEntities()` | `List` | Detected entities, never `null`. See [`DetectedEntity`](#detectedentity). | +| `getMetrics()` | `Metrics` | Word and character counts. See [`Metrics`](#metrics). | -### `ReidentifyTextResponse` +### `ReidentifyStringResponse` -`com.skyflow.vault.detect` — returned by `detect().reidentifyText()`. +`com.skyflow.detect` — returned by `detect().reidentifyString()`. | Getter | Return type | Description | |--------|-------------|-------------| -| `getProcessedText()` | `String` | The re-identified text with tokens replaced by their original values. | +| `getProcessedText()` | `String` | The re-identified text. | +| `getMetrics()` | `Metrics` | Word and character counts. | ### `DeidentifyFileResponse` -`com.skyflow.vault.detect` — returned by `detect().deidentifyFile()`. +`com.skyflow.detect` — returned by `detect().deidentifyFile()`. Without `pollOptions` only `getRunId()` is set. + +| Getter | Return type | Description | +|--------|-------------|-------------| +| `getRunId()` | `String` | Run id, always present. | +| `getStatus()` | `DetectRunStatus` | Run status when polled, `null` when submit only. See [`DetectRunStatus`](#detectrunstatus). | +| `getOutputType()` | `DataSourceType` | `BASE64` or `PRESIGNED_URL`, `null` until the run completes. | +| `getOutput()` | `List` | Every output of the run, empty until complete, never `null`. See [`FileOutput`](#fileoutput). | +| `getMetrics()` | `Metrics` | Size, counts, pages, slides, duration. `null` until complete. | +| `getMessage()` | `String` | Failure detail when the status is `FAILED`. | + +### `ReidentifyFileResponse` + +`com.skyflow.detect` — returned by `detect().reidentifyFile()`. | Getter | Return type | Description | |--------|-------------|-------------| -| `getFile()` | `FileInfo` | Metadata about the processed file. See [`FileInfo`](#fileinfo). | -| `getFileBase64()` | `String` | Base64-encoded processed file content (when `outputProcessedImage=true`). | -| `getType()` | `String` | MIME type of the output file. | -| `getExtension()` | `String` | File extension of the output file. | -| `getWordCount()` | `Integer` | Word count (text/document files). | -| `getCharCount()` | `Integer` | Character count (text/document files). | -| `getSizeInKb()` | `Float` | Output file size in kilobytes. | -| `getDurationInSeconds()` | `Float` | Duration in seconds (audio/video files). | -| `getPageCount()` | `Integer` | Page count (PDF files). | -| `getSlideCount()` | `Integer` | Slide count (presentation files). | -| `getEntities()` | `List` | Detected entities. See [`FileEntityInfo`](#fileentityinfo). | -| `getRunId()` | `String` | Run ID for async polling with `getDetectRun()`. | -| `getStatus()` | `String` | Processing status. See [`DeidentifyFileStatus`](#deidentifyfilestatus). | +| `getStatus()` | `DetectRunStatus` | Status of the re-identification. | +| `getOutputType()` | `DataSourceType` | `BASE64` or `PRESIGNED_URL`. | +| `getOutput()` | `List` | Re-identified file outputs, never `null`. | +| `getMetrics()` | `Metrics` | Size and counts. | + +### `GetRunResponse` + +`com.skyflow.detect` — returned by `detect().getRun()`. Same getters as [`DeidentifyFileResponse`](#deidentifyfileresponse). + +### `CheckGuardrailsResponse` + +`com.skyflow.detect` — returned by `detect().checkGuardrails()`. + +| Getter | Return type | Description | +|--------|-------------|-------------| +| `getText()` | `String` | The screened text. | +| `getValidation()` | `GuardrailsValidation` | `PASSED` or `FAILED`. See [`GuardrailsValidation`](#guardrailsvalidation). | +| `getToxic()` | `Boolean` | Whether the text was judged toxic, `null` when the check did not run. | +| `getDeniedTopic()` | `Boolean` | Whether a denied topic was found, `null` when no topics were supplied. | ### `InvokeConnectionResponse` @@ -444,117 +472,137 @@ Each element returned by `getDetokenizedFields()` and `getErrors()`. | `getValue()` | `String` | The value to tokenize. | | `getColumnGroup()` | `String` | The column group name. | -### `FileInput` +### `DetectConfiguration` -`com.skyflow.vault.detect` — used inside [`DeidentifyFileRequest`](#deidentifyfilerequest). Provide exactly one source. +`com.skyflow.detect` — inline Detect policy for `deidentifyString` and `deidentifyFile`. | Builder method | Default | Description | |----------------|---------|-------------| -| `file(File)` | `null` | A `java.io.File` object. | -| `filePath(String)` | `null` | Path to a file. | +| `name(String)` | `null` | Configuration name. | +| `description(String)` | `null` | Configuration description. | +| `detect(Detect)` | `null` | What to detect and how to de-identify it. See [`Detect`](#detect). | +| `fileMapping(List)` | `null` | Per-column handling for structured files. See [`FileMapping`](#filemapping). | +| `media(Media)` | `null` | Audio, document and image options for file calls. See [`Media`](#media). | -| Getter | Return type | Description | -|--------|-------------|-------------| -| `getFile()` | `File` | The file object. | -| `getFilePath()` | `String` | The file path. | +### `Detect` -### `AudioBleep` +| Builder method | Default | Description | +|----------------|---------|-------------| +| `entities(List)` | `null` | Entities to detect, each with its own de-identification type. See [`Entity`](#entity). | +| `objectEntities(List)` | `null` | Visual objects to detect in images. See [`ObjectEntity`](#objectentity). | +| `restrict(List)` | `null` | Regexes to always treat as restricted. | +| `skip(List)` | `null` | Regexes to never treat as sensitive. | +| `customTypes(List)` | `null` | Regex-defined entity types. See [`CustomType`](#customtype). | +| `returnEntities(ReturnEntitiesType)` | `EXCLUDE_SENSITIVE_DATA` | Whether raw values come back in the response. See [`ReturnEntitiesType`](#returnentitiestype). | -`com.skyflow.vault.detect` — used inside [`DeidentifyFileRequest`](#deidentifyfilerequest) for audio bleeping. +### `Entity` | Builder method | Default | Description | |----------------|---------|-------------| -| `gain(Double)` | `null` | Gain level of the bleep tone. | -| `frequency(Double)` | `null` | Frequency (Hz) of the bleep tone. | -| `startPadding(Double)` | `null` | Seconds of silence before the bleep. | -| `stopPadding(Double)` | `null` | Seconds of silence after the bleep. | +| `entityType(EntityType)` | `ALL` | Entity type. See [`EntityType`](#entitytype). | +| `deidentificationType(DeidentificationType)` | `ENTITY_UNIQUE_COUNTER` | How the value is replaced. See [`DeidentificationType`](#deidentificationtype). | +| `destination(String)` | `null` | For `VAULT_TOKEN`: the `table.column` that stores the value. | +| `transformation(Transformation)` | `null` | Date shifting. See [`Transformation`](#transformation). | -| Getter | Return type | Description | -|--------|-------------|-------------| -| `getGain()` | `Double` | Gain level. | -| `getFrequency()` | `Double` | Frequency. | -| `getStartPadding()` | `Double` | Start padding in seconds. | -| `getStopPadding()` | `Double` | Stop padding in seconds. | +### `Transformation` and `ShiftDates` -### `TokenFormat` +`Transformation.builder().shiftDates(ShiftDates)`; `ShiftDates.builder().minDays(Integer).maxDays(Integer)`. Dates are shifted by a random amount within the range. -`com.skyflow.vault.detect` — used inside [`DeidentifyTextRequest`](#deidentifytextrequest) and [`DeidentifyFileRequest`](#deidentifyfilerequest) to control token types per entity. +### `CustomType` | Builder method | Default | Description | |----------------|---------|-------------| -| `defaultType(TokenType)` | `TokenType.ENTITY_UNIQUE_COUNTER` | Default token type for entities not explicitly listed. See [`TokenType`](#tokentype). | -| `vaultToken(List)` | `null` | Entities to tokenize as vault tokens. | -| `entityUniqueCounter(List)` | `null` | Entities to tokenize as entity-unique-counter tokens. | -| `entityOnly(List)` | `null` | Entities to tokenize as entity-only tokens. | +| `label(String)` | `null` | Becomes the entity type on the response. | +| `match(List)` | `null` | Regexes that define the type. | -### `Transformations` +### `ObjectEntity` -`com.skyflow.vault.detect` — used inside [`DeidentifyTextRequest`](#deidentifytextrequest) and [`DeidentifyFileRequest`](#deidentifyfilerequest). +| Builder method | Default | Description | +|----------------|---------|-------------| +| `entityType(ObjectEntityType)` | `null` | `FACE`, `LICENSE_PLATE`, `LOGO`, `SIGNATURE` or `ALL`. | +| `deidentificationType(ObjectDeidentificationType)` | `null` | `REDACT` or `UNREDACT`. | -| Constructor | Description | -|-------------|-------------| -| `new Transformations(DateTransformation shiftDates)` | Apply date shifting. | +### `FileMapping` -| Getter | Return type | Description | -|--------|-------------|-------------| -| `getShiftDates()` | `DateTransformation` | The date transformation to apply. | +| Builder method | Description | +|----------------|-------------| +| `source(String)` | Source column. | +| `destination(String)` | Destination column. | +| `outputFileNameSuffix(String)` | Suffix added to the output file name. | +| `entitiesDestination(String)` | Column that receives the detected entities. | +| `objectEntitiesDestination(String)` | Column that receives the detected object entities. | -### `DateTransformation` +### `Media` -`com.skyflow.vault.detect` — used inside [`Transformations`](#transformations). +`Media.builder().audio(Audio).document(Document).image(Image)`. -| Constructor | Description | -|-------------|-------------| -| `new DateTransformation(int max, int min, List entities)` | Shift dates by a random amount within `[min, max]` days. | +| Class | Builder methods | +|-------|-----------------| +| `Audio` | `outputProcessedAudio(Boolean)`, `outputTranscription(OutputTranscriptionType)`, `bleep(Bleep)` | +| `Bleep` | `startPadding(Float)`, `stopPadding(Float)`, `frequency(Integer)`, `gain(Integer)` | +| `Document` | `pdf(Pdf)` | +| `Pdf` | `processingMode(PdfProcessingMode)`, `density(Integer)`, `maxResolution(Integer)` | +| `Image` | `outputProcessedImage(Boolean)`, `outputOcrText(Boolean)`, `maskingMethod(MaskingMethod)` | -| Getter | Return type | Description | -|--------|-------------|-------------| -| `getMax()` | `int` | Maximum day-shift value. | -| `getMin()` | `int` | Minimum day-shift value. | -| `getEntities()` | `List` | Entity types to date-shift. | +### `PollOptions` -### `EntityInfo` +`com.skyflow.detect` — opts `deidentifyFile` into submit-and-poll mode. The SDK polls with exponential backoff (1, 2, 4, 8, 16, then 32 seconds) on the calling thread. -`com.skyflow.vault.detect` — element of `DeidentifyTextResponse.getEntities()`. +| Builder method | Default | Description | +|----------------|---------|-------------| +| `waitTime(Integer)` | `60` | Maximum total seconds to keep polling, 1 to 300. | +| `maxAttempts(Integer)` | `23` | Maximum number of run lookups, 1 to 23. | -| Getter | Return type | Description | -|--------|-------------|-------------| -| `getToken()` | `String` | The token that replaced the original entity value. | -| `getValue()` | `String` | The original entity value. | -| `getTextIndex()` | `TextIndex` | Character offsets of the entity in the original text. | -| `getProcessedIndex()` | `TextIndex` | Character offsets of the token in the processed text. | -| `getEntity()` | `String` | Entity type label (e.g. `"EMAIL_ADDRESS"`). | -| `getScores()` | `Map` | Confidence scores per entity type. | +### `RedactionLevel` + +`com.skyflow.detect` — element of `ReidentifyStringRequest.redactionLevel()`. For skyvault vaults name an entity and a redaction type. + +| Builder method | Description | +|----------------|-------------| +| `entityName(EntityType)` | Entity the rule applies to. | +| `redactionType(RedactionType)` | `PLAIN_TEXT`, `MASKED`, `REDACTED` or `DEFAULT`. See [`RedactionType`](#redactiontype). | +| `tokenGroupName(String)` | Flowvault vaults only. | +| `redactionPattern(String)` | Flowvault vaults only. | -### `TextIndex` +### `DetectedEntity` -`com.skyflow.vault.detect` — used in [`EntityInfo`](#entityinfo). +`com.skyflow.detect` — element of `DeidentifyStringResponse.getEntities()`. | Getter | Return type | Description | |--------|-------------|-------------| -| `getStart()` | `int` | Start character offset (inclusive). | -| `getEnd()` | `int` | End character offset (exclusive). | +| `getToken()` | `String` | The token that replaced the value, e.g. `NAME_1`. | +| `getValue()` | `String` | The original value; empty unless `returnEntities` is `ALL`. | +| `getLocation()` | `EntityLocation` | Offsets in the original and processed text. | +| `getEntityType()` | `String` | Entity type label, including custom type labels. | +| `getEntityScores()` | `Map` | Confidence scores per entity type. | -### `FileEntityInfo` +### `EntityLocation` -`com.skyflow.vault.detect` — element of `DeidentifyFileResponse.getEntities()`. +| Getter | Return type | Description | +|--------|-------------|-------------| +| `getStartIndex()` / `getEndIndex()` | `Integer` | Offsets into the original text. | +| `getStartIndexProcessed()` / `getEndIndexProcessed()` | `Integer` | Offsets into the processed text. | + +### `Metrics` | Getter | Return type | Description | |--------|-------------|-------------| -| `getFile()` | `String` | File name or identifier. | -| `getType()` | `String` | Output file type. | -| `getExtension()` | `String` | Output file extension. | +| `getSize()` | `Double` | Size in kilobytes. | +| `getWordCount()` | `Integer` | Word count. | +| `getCharacterCount()` | `Integer` | Character count. | +| `getPages()` | `Integer` | Page count, documents only. | +| `getSlides()` | `Integer` | Slide count, presentations only. | +| `getDuration()` | `Double` | Duration in seconds, audio only. | -### `FileInfo` +### `FileOutput` -`com.skyflow.vault.detect` — returned by `DeidentifyFileResponse.getFile()`. +`com.skyflow.detect` — element of `getOutput()` on the file responses. | Getter | Return type | Description | |--------|-------------|-------------| -| `getName()` | `String` | Original file name. | -| `getSize()` | `long` | File size in bytes. | -| `getType()` | `String` | MIME type. | -| `getLastModified()` | `long` | Last-modified timestamp (milliseconds since epoch). | +| `getProcessedFile()` | `String` | Base64 content or a presigned URL, per the response's `getOutputType()`. | +| `getProcessedFileType()` | `String` | `REDACTED_FILE`, `ENTITIES`, `OBJECT_ENTITIES`, `REDACTED_TEXT`, and so on. | +| `getProcessedFileExtension()` | `FileDataFormat` | Extension of the output. | --- @@ -604,16 +652,6 @@ Each element returned by `getDetokenizedFields()` and `getErrors()`. | `ENABLE` | Use provided tokens where supplied; generate tokens for missing fields. | | `ENABLE_STRICT` | All fields must supply a BYOT token; missing tokens cause an error. | -### `TokenType` - -`com.skyflow.enums` — used in [`TokenFormat`](#tokenformat) for Detect operations. - -| Value | Description | -|-------|-------------| -| `VAULT_TOKEN` | Token stored in the vault and associated with a skyflow_id. | -| `ENTITY_UNIQUE_COUNTER` | Deterministic token unique to the entity value (consistent across occurrences). | -| `ENTITY_ONLY` | Token represents the entity type only, with no value stored in the vault. | - ### `RequestMethod` `com.skyflow.enums` — used in [`InvokeConnectionRequest`](#invokeconnectionrequest). @@ -626,54 +664,25 @@ Each element returned by `getDetokenizedFields()` and `getErrors()`. | `PATCH` | HTTP PATCH. | | `DELETE` | HTTP DELETE. | -### `MaskingMethod` - -`com.skyflow.enums` — used in [`DeidentifyFileRequest`](#deidentifyfilerequest). - -| Value | Description | -|-------|-------------| -| `BLACKBOX` | Cover detected entities with a solid black rectangle. | -| `BLUR` | Blur detected entities. | - -### `DetectOutputTranscriptions` - -`com.skyflow.enums` — used in [`DeidentifyFileRequest`](#deidentifyfilerequest). - -| Value | Description | -|-------|-------------| -| `TRANSCRIPTION` | Standard transcription. | -| `DIARIZED_TRANSCRIPTION` | Transcription with speaker diarization. | -| `MEDICAL_TRANSCRIPTION` | Medical-domain transcription. | -| `MEDICAL_DIARIZED_TRANSCRIPTION` | Medical transcription with speaker diarization. | - -### `DeidentifyFileStatus` - -`com.skyflow.enums` — returned in `DeidentifyFileResponse.getStatus()`. - -| Value | Description | -|-------|-------------| -| `IN_PROGRESS` | File processing is ongoing. Poll with `getDetectRun()`. | -| `SUCCESS` | Processing completed successfully. | -| `FAILED` | Processing failed. | -| `UNKNOWN` | Status could not be determined. | - -### `DetectEntities` - -`com.skyflow.enums` — entity type values for Detect operations. - -| Category | Values | -|----------|--------| -| Personal identity | `NAME`, `NAME_GIVEN`, `NAME_FAMILY`, `NAME_MEDICAL_PROFESSIONAL`, `DOB`, `AGE`, `GENDER`, `MARITAL_STATUS`, `SEXUALITY`, `RELIGION`, `POLITICAL_AFFILIATION`, `PHYSICAL_ATTRIBUTE`, `ORIGIN`, `NATIONALITY` | -| Contact | `EMAIL_ADDRESS`, `PHONE_NUMBER`, `LOCATION`, `LOCATION_ADDRESS`, `LOCATION_ADDRESS_STREET`, `LOCATION_CITY`, `LOCATION_STATE`, `LOCATION_COUNTRY`, `LOCATION_ZIP`, `LOCATION_COORDINATE` | -| Financial | `CREDIT_CARD`, `CREDIT_CARD_EXPIRATION`, `CVV`, `BANK_ACCOUNT`, `ACCOUNT_NUMBER`, `ROUTING_NUMBER`, `MONEY`, `FINANCIAL_METRIC`, `CORPORATE_ACTION` | -| Government ID | `SSN`, `DRIVER_LICENSE`, `PASSPORT_NUMBER`, `HEALTHCARE_NUMBER`, `ORGANIZATION_ID`, `NUMERICAL_PII` | -| Medical | `BLOOD_TYPE`, `CONDITION`, `DRUG`, `DOSE`, `EFFECT`, `INJURY`, `MEDICAL_CODE`, `MEDICAL_PROCESS`, `ORGANIZATION_MEDICAL_FACILITY` | -| Date & time | `DATE`, `DAY`, `MONTH`, `YEAR`, `TIME`, `DURATION`, `DATE_INTERVAL`, `EVENT` | -| Technology | `IP_ADDRESS`, `URL`, `USERNAME`, `PASSWORD`, `FILENAME`, `VEHICLE_ID` | -| Organization | `ORGANIZATION`, `OCCUPATION`, `PROJECT`, `PRODUCT` | -| Other | `LANGUAGE`, `STATISTICS`, `TREND`, `ZODIAC_SIGN`, `ALL` | - -Use `DetectEntities.ALL` to detect all supported entity types. +### Detect enums + +All in `com.skyflow.detect`. + +| Enum | Values | +|------|--------| +| `EntityType` | the 70 entity types (`NAME`, `EMAIL_ADDRESS`, `SSN`, `CREDIT_CARD`, `DOB`, ...), plus `ALL` and `NONE` | +| `DeidentificationType` | `ENTITY_UNIQUE_COUNTER` _(default)_, `ENTITY_ONLY`, `VAULT_TOKEN`, `MASK`, `UNKNOWN` | +| `DataSourceType` | `BASE64`, `SKYFLOW_ID`, `PRESIGNED_URL` | +| `FileDataFormat` | `BMP`, `CSV`, `DCM`, `DOC`, `DOCX`, `GIF`, `JPEG`, `JPG`, `JSON`, `JSONL`, `MP3`, `PDF`, `PNG`, `PPT`, `PPTX`, `TIF`, `TIFF`, `TXT`, `WAV`, `XLS`, `XLSX`, `XML`, `ZIP` | +| `DetectRunStatus` | `QUEUED`, `IN_PROGRESS`, `SUCCESS`, `FAILED`, `UNKNOWN`. `SUCCESS`, `FAILED` and `UNKNOWN` end polling. | +| `ReturnEntitiesType` | `EXCLUDE_SENSITIVE_DATA` _(default)_, `ALL`, `NONE` | +| `RedactionType` | `PLAIN_TEXT`, `MASKED`, `REDACTED`, `DEFAULT` | +| `MaskingMethod` | `NONE`, `BLUR`, `BLACKBOX` | +| `OutputTranscriptionType` | `NONE`, `TRANSCRIPTION`, `MEDICAL_TRANSCRIPTION`, `DIARIZED_TRANSCRIPTION`, `MEDICAL_DIARIZED_TRANSCRIPTION` | +| `PdfProcessingMode` | `NONE`, `OCR`, `TEXT_LAYER` | +| `ObjectEntityType` | `NONE`, `FACE`, `LICENSE_PLATE`, `LOGO`, `SIGNATURE`, `ALL` | +| `ObjectDeidentificationType` | `UNKNOWN`, `REDACT`, `UNREDACT` | +| `GuardrailsValidation` | `PASSED`, `FAILED`, `UNKNOWN` | --- diff --git a/flowvault/README.md b/flowvault/README.md index c6d78f26..378de9a0 100644 --- a/flowvault/README.md +++ b/flowvault/README.md @@ -49,6 +49,11 @@ The `flowvault` module is a Skyflow Java SDK built for high-throughput vault ope - [Get](#get) - [Update](#update) - [Delete](#delete) +- [Detect](#detect) + - [Deidentify string](#deidentify-string) + - [Reidentify string](#reidentify-string) + - [Get run](#get-run) + - [Check guardrails](#check-guardrails) - [Custom Request Headers](#custom-request-headers) - [Error Handling](#error-handling) - [Two layers of errors](#two-layers-of-errors) @@ -1624,6 +1629,275 @@ for (DeleteResponseRecord record : deleteResponse.getRecords()) { } ``` +# Detect + +Skyflow Detect finds and de-identifies sensitive data in free text, then re-identifies it on demand. The flowvault SDK exposes the Detect V2 API through `DetectController`, returned by `skyflowClient.detect()` and `skyflowClient.detect(vaultId)`. Every request is scoped to that vault, and the controller honours the same credentials, [timeouts and retries](#timeouts-and-retries) as `vault()`. + +Detect configurations are created in Studio or through the management API. The SDK does not create, update or delete them. + +| Method | Request | Response | Description | +|--------|---------|----------|-------------| +| `deidentifyString(DeidentifyStringRequest)` | `com.skyflow.detect.DeidentifyStringRequest` | `com.skyflow.detect.DeidentifyStringResponse` | Detect and replace sensitive data in a string | +| `deidentifyFile(DeidentifyFileRequest)` | `com.skyflow.detect.DeidentifyFileRequest` | `com.skyflow.detect.DeidentifyFileResponse` | Submit a file for de-identification, optionally polling the run to completion | +| `reidentifyString(ReidentifyStringRequest)` | `com.skyflow.detect.ReidentifyStringRequest` | `com.skyflow.detect.ReidentifyStringResponse` | Replace tokens in a string with their original or redacted values | +| `reidentifyFile(ReidentifyFileRequest)` | `com.skyflow.detect.ReidentifyFileRequest` | `com.skyflow.detect.ReidentifyFileResponse` | Replace tokens in a file with their original or redacted values | +| `getRun(GetRunRequest)` | `com.skyflow.detect.GetRunRequest` | `com.skyflow.detect.GetRunResponse` | Retrieve the status and outputs of a Detect file run | +| `checkGuardrails(CheckGuardrailsRequest)` | `com.skyflow.detect.CheckGuardrailsRequest` | `com.skyflow.detect.CheckGuardrailsResponse` | Screen text for toxicity and denied topics | + +> Detect V2 is in beta. + +## Deidentify string + +`DeidentifyStringRequest` takes the text plus, optionally, `configurationId` (a stored Detect configuration) and/or `configuration` (an inline `DetectConfiguration`). Both are optional on the API and are sent exactly as supplied. The SDK fills the vault id from the controller. + +```java +import com.skyflow.detect.*; + +// Stored configuration +DeidentifyStringResponse response = skyflowClient.detect().deidentifyString( + DeidentifyStringRequest.builder() + .text("My name is John Doe, and my email is johndoe@acme.com.") + .configurationId("") + .build()); + +System.out.println(response.getProcessedText()); +// My name is [NAME_1], and my email is [EMAIL_ADDRESS_1]. + +// Inline configuration +DetectConfiguration configuration = DetectConfiguration.builder() + .detect(Detect.builder() + .entities(Arrays.asList( + Entity.builder() + .entityType(EntityType.NAME) + .deidentificationType(DeidentificationType.VAULT_TOKEN) + .destination("") // token group that stores the value + .build(), + Entity.builder() + .entityType(EntityType.ALL) + .deidentificationType(DeidentificationType.ENTITY_UNIQUE_COUNTER) + .build())) + .skip(Collections.singletonList("Skyflow")) + .returnEntities(ReturnEntitiesType.EXCLUDE_SENSITIVE_DATA) + .build()) + .build(); + +response = skyflowClient.detect().deidentifyString( + DeidentifyStringRequest.builder() + .text("My name is John Doe, and my email is johndoe@acme.com.") + .configuration(configuration) + .build()); + +for (DetectedEntity entity : response.getEntities()) { + System.out.println(entity.getEntityType() + " " + entity.getToken() + + " [" + entity.getLocation().getStartIndex() + "," + entity.getLocation().getEndIndex() + "]"); +} +System.out.println(response.getMetrics().getWordCount()); +``` + +`DeidentifyStringResponse` carries `getProcessedText()`, `getEntities()` (a `List` with token, entity type, location and confidence scores; never `null`) and `getMetrics()`. + +## Deidentify file + +File de-identification is asynchronous on the API: the submit call returns a run id and the result is retrieved from the run. `deidentifyFile` exposes both modes. + +- **Submit only** (default): one call, returns `getRunId()`. `getStatus()` is `null` and nothing is written to disk. Retrieve the result later with [`getRun`](#get-run). +- **Submit and poll**: set `pollOptions`. The SDK polls the run with exponential backoff (1, 2, 4, 8, 16, then 32 seconds between lookups) until it is `SUCCESS`, `FAILED` or `UNKNOWN`, or until `waitTime` (default 60 s, max 300) or `maxAttempts` (default 23, max 23) is used up. If the budget runs out the response carries the run id with `IN_PROGRESS` or `QUEUED` so you can resume with `getRun`. + +The file is supplied in one of three ways: `dataSource` plus `value` (`BASE64` content, a `SKYFLOW_ID`, or a `PRESIGNED_URL`), or `file(File)` / `filePath(String)`, which read and encode a local file and infer `dataFormat` from its extension. Supply exactly one of `value`, `file` or `filePath`. Either `configurationId` or an inline `configuration` is passed through as given. + +```java +// Submit only +DeidentifyFileResponse submitted = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("/data/intake/patient-notes.pdf") // BASE64 + pdf inferred + .configurationId("") + .build()); +String runId = submitted.getRunId(); + +// Submit and poll +DeidentifyFileResponse response = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("/data/intake/patient-notes.pdf") + .configurationId("") + .pollOptions(PollOptions.builder().waitTime(120).build()) + .outputDirectory("/data/processed") // optional + .build()); + +switch (response.getStatus()) { + case SUCCESS: + // For file-based requests the outputs are already on disk: + // /data/processed/processed-patient-notes.pdf the redacted file + // /data/processed/processed-entities-patient-notes.json the detected entities + // response.getOutput() and getMetrics() carry the same data. + break; + case FAILED: + System.err.println(response.getMessage()); + break; + default: // IN_PROGRESS or QUEUED: budget ran out, resume with getRun(runId) + break; +} +``` + +Outputs are written only when polling reached `SUCCESS`, the request was built from a local file, and the run delivered them as base64. A request built from a `SKYFLOW_ID` or `PRESIGNED_URL` has no local name to derive from, and presigned-URL outputs are not fetched, so in those cases read `getOutput()` and write the files yourself. Files are named `processed-.`, with the entities output as `processed-entities-.json` (and `processed-object-entities-.json` for object entities); `outputDirectory` is created if missing and defaults to the working directory. Polling blocks the calling thread. + +### Polling from a worker thread + +With `pollOptions` set, `deidentifyFile` polls on the thread that called it: each lookup is a synchronous `getRun` followed by a sleep, until the run is terminal or the budget runs out. No other thread, lock or connection is held while it waits, so other SDK calls are unaffected, but the calling thread is. If that thread is your main thread, a request thread or an event loop, run the call elsewhere. + +**Run the blocking call on a thread you own.** Simplest when you process a few files at a time. The SDK still enforces the budget and writes outputs to disk; your thread is parked for the whole poll. + +```java +ExecutorService pool = Executors.newFixedThreadPool(4); // or Executors.newVirtualThreadPerTaskExecutor() on JDK 21+ + +pool.execute(() -> { + try { + DeidentifyFileResponse response = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("/data/intake/patient-notes.pdf") + .configurationId("") + .pollOptions(PollOptions.builder().waitTime(120).build()) + .outputDirectory("/data/processed") + .build()); + handle(response); // SUCCESS, FAILED, UNKNOWN, or IN_PROGRESS/QUEUED if the budget ran out + } catch (SkyflowException e) { + handleError(e); // catch inside the task; an uncaught exception only ends this thread + } +}); +``` + +Use `pool.submit(...)` instead of `execute` if you want a `Future` to cancel with: interrupting the thread wakes the sleep and the SDK returns the last run it saw. Bound the pool, since every in-flight run parks one thread. + +**Submit only, then poll `getRun` on a scheduler.** Best for services and anything concurrent. No thread is held between lookups, so one scheduler thread serves any number of runs. You control the backoff and budget, and you write the outputs yourself since the SDK only writes them when it polls. + +```java +ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); + +String runId = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("/data/intake/patient-notes.pdf") + .configurationId("") + .build()) // no pollOptions: returns the run id immediately + .getRunId(); + +scheduler.schedule(new Runnable() { + long delaySeconds = 1; + + @Override + public void run() { + try { + GetRunResponse run = skyflowClient.detect().getRun(GetRunRequest.builder().runId(runId).build()); + switch (run.getStatus()) { + case SUCCESS: case FAILED: case UNKNOWN: + handle(run); + return; + default: // QUEUED, IN_PROGRESS + scheduler.schedule(this, delaySeconds, TimeUnit.SECONDS); + delaySeconds = Math.min(delaySeconds * 2, 32); + } + } catch (SkyflowException e) { + handleError(e); + } + } +}, 0, TimeUnit.SECONDS); +``` + +Either way the main thread only pays for the submit round trip. Avoid `new Thread(...)` per file or `CompletableFuture.runAsync` on the common pool for anything that runs at scale: the first has no bound on threads, and the second blocks a shared pool sized for CPU work. + +## Reidentify string + +`ReidentifyStringRequest` takes the tokenized text and an optional list of `RedactionLevel` rules. For flowvault vaults each rule targets a `tokenGroupName` and applies a named `redactionPattern`. Without rules every token is replaced by its original value. + +```java +ReidentifyStringResponse response = skyflowClient.detect().reidentifyString( + ReidentifyStringRequest.builder() + .text("My name is [NAME_1].") + .redactionLevel(Collections.singletonList( + RedactionLevel.builder() + .tokenGroupName("") + .redactionPattern("") + .build())) + .build()); + +System.out.println(response.getProcessedText()); +// My name is J**n D*e. +``` + +A `RedactionLevel` is expected to name one source (`tokenGroupName` or `entityName`) and one replacement (`redactionPattern` or `redactionType`). Every field is optional on the API, so the SDK passes the list through as given and the server enforces the combination rules, including which fields apply to flowvault vaults. + +## Reidentify file + +`reidentifyFile` is synchronous: the re-identified file comes back in the response, not through a run id. `ReidentifyFileRequest` takes a `dataSource` (`BASE64`, `SKYFLOW_ID` or `PRESIGNED_URL`), the matching `value`, an optional `dataFormat` and the same optional `RedactionLevel` rules as `reidentifyString`. Re-identification supports text-based formats such as TXT, CSV, JSON, JSONL, XML, DOCX, XLSX and PPTX. + +```java +byte[] content = Files.readAllBytes(Paths.get("tokenized.txt")); + +ReidentifyFileResponse response = skyflowClient.detect().reidentifyFile( + ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64) + .value(Base64.getEncoder().encodeToString(content)) + .dataFormat(FileDataFormat.TXT) + .redactionLevel(Collections.singletonList( + RedactionLevel.builder() + .tokenGroupName("") + .redactionPattern("") + .build())) + .build()); + +if (response.getStatus() == DetectRunStatus.SUCCESS) { + for (FileOutput output : response.getOutput()) { + // output.getProcessedFile() is base64 or a presigned URL, per response.getOutputType() + byte[] processed = Base64.getDecoder().decode(output.getProcessedFile()); + } +} +``` + +`ReidentifyFileResponse` carries `getStatus()`, `getOutputType()`, `getOutput()` (never `null`) and `getMetrics()`. + +## Get run + +File de-identification is asynchronous: the submit call returns a run id, and `getRun` retrieves the run's status and, once it has succeeded, its outputs. `GetRunResponse.getOutput()` is empty and `getOutputType()` and `getMetrics()` are `null` until the run completes. + +```java +GetRunResponse run = skyflowClient.detect().getRun( + GetRunRequest.builder().runId("").build()); + +switch (run.getStatus()) { + case SUCCESS: + for (FileOutput output : run.getOutput()) { + // output.getProcessedFile() is base64 or a presigned URL, per run.getOutputType() + // output.getProcessedFileType() is e.g. REDACTED_FILE or ENTITIES + // output.getProcessedFileExtension() is a FileDataFormat such as PDF + } + break; + case FAILED: + System.err.println(run.getMessage()); + break; + default: // QUEUED, IN_PROGRESS, UNKNOWN + // poll again later +} +``` + +## Check guardrails + +`checkGuardrails` screens text for toxicity and for a list of denied topics, which makes it a natural pre-LLM check. Each check runs only when requested: `getToxic()` is `null` unless `checkToxicity(true)` was set, and `getDeniedTopic()` is `null` unless `denyTopics` was supplied. `getValidation()` is `FAILED` if any requested check triggered. + +```java +CheckGuardrailsResponse response = skyflowClient.detect().checkGuardrails( + CheckGuardrailsRequest.builder() + .text(userPrompt) + .checkToxicity(true) + .denyTopics(Arrays.asList("politics", "medical advice")) + .build()); + +if (response.getValidation() == GuardrailsValidation.FAILED) { + throw new IllegalArgumentException("blocked: toxic=" + response.getToxic() + " deniedTopic=" + response.getDeniedTopic()); +} +``` + +All Detect methods throw `SkyflowException` as described in [Error Handling](#error-handling). Client-side validation fails before any network call. + +See the samples [DeidentifyStringSample.java](samples/src/main/java/com/example/detect/DeidentifyStringSample.java), [DeidentifyFileSample.java](samples/src/main/java/com/example/detect/DeidentifyFileSample.java), [ReidentifyStringSample.java](samples/src/main/java/com/example/detect/ReidentifyStringSample.java), [ReidentifyFileSample.java](samples/src/main/java/com/example/detect/ReidentifyFileSample.java), [GetRunSample.java](samples/src/main/java/com/example/detect/GetRunSample.java) and [CheckGuardrailsSample.java](samples/src/main/java/com/example/detect/CheckGuardrailsSample.java). + # Custom Request Headers To include custom HTTP headers on an outgoing request — bulk or unary — pass a `RequestInterceptor` via that operation's options object. The headers available are defined by the `CustomHeaderKey` enum: diff --git a/flowvault/api-report/skyflow-flowvault-java.baseline.jar b/flowvault/api-report/skyflow-flowvault-java.baseline.jar index 1defab78..813b5c66 100644 Binary files a/flowvault/api-report/skyflow-flowvault-java.baseline.jar and b/flowvault/api-report/skyflow-flowvault-java.baseline.jar differ diff --git a/flowvault/pom.xml b/flowvault/pom.xml index 6ea99c9a..43a57f15 100644 --- a/flowvault/pom.xml +++ b/flowvault/pom.xml @@ -12,7 +12,7 @@ skyflow-flowvault-java - 1.2.0 + 1.2.0-dev.225f34ec jar ${project.groupId}:${project.artifactId} Skyflow FlowVault SDK for the Java programming language @@ -48,6 +48,12 @@ 1.0.0 compile + + com.squareup.okhttp3 + mockwebserver + ${okhttp-version} + test + @@ -76,25 +82,18 @@ - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.6.0 - + shade-for-japicmp package @@ -180,7 +179,7 @@ jfrog - central + skyflow-jfrog prekarilabs.jfrog.io-releases https://prekarilabs.jfrog.io/artifactory/skyflow-java diff --git a/flowvault/samples/src/main/java/com/example/detect/CheckGuardrailsSample.java b/flowvault/samples/src/main/java/com/example/detect/CheckGuardrailsSample.java new file mode 100644 index 00000000..a48efaf2 --- /dev/null +++ b/flowvault/samples/src/main/java/com/example/detect/CheckGuardrailsSample.java @@ -0,0 +1,53 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.CheckGuardrailsResponse; +import com.skyflow.detect.GuardrailsValidation; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.util.Arrays; + +/** + * Screens a prompt for toxicity and denied topics before it is sent to an LLM. + */ +public class CheckGuardrailsSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + String userPrompt = "Which party should I vote for?"; + try { + CheckGuardrailsResponse response = skyflowClient.detect().checkGuardrails( + CheckGuardrailsRequest.builder() + .text(userPrompt) + .checkToxicity(true) + .denyTopics(Arrays.asList("politics", "medical advice")) + .build()); + + if (response.getValidation() == GuardrailsValidation.FAILED) { + System.out.println("Blocked: toxic=" + response.getToxic() + " deniedTopic=" + response.getDeniedTopic()); + } else { + System.out.println("Prompt passed guardrails."); + } + } catch (SkyflowException e) { + System.err.println("Error during checkGuardrails:"); + e.printStackTrace(); + } + } +} diff --git a/flowvault/samples/src/main/java/com/example/detect/DeidentifyFileSample.java b/flowvault/samples/src/main/java/com/example/detect/DeidentifyFileSample.java new file mode 100644 index 00000000..c373f181 --- /dev/null +++ b/flowvault/samples/src/main/java/com/example/detect/DeidentifyFileSample.java @@ -0,0 +1,66 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyFileResponse; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.PollOptions; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +/** + * De-identifies a local file with the Detect V2 API. The first call submits the run and returns its + * id; the second submits and polls, and writes the outputs next to the input on success. + */ +public class DeidentifyFileSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + try { + // Submit only: the API's own behaviour. Keep the run id and retrieve the result with getRun. + DeidentifyFileResponse submitted = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("") // BASE64 and the format are derived from the file + .configurationId("") // Replace with a Detect configuration id + .build()); + System.out.println("Submitted run " + submitted.getRunId()); + + // Submit and poll: waits up to 90 seconds with exponential backoff, then writes + // processed-. and processed-.json into the output directory. + DeidentifyFileResponse polled = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("") + .configurationId("") + .pollOptions(PollOptions.builder().waitTime(90).build()) + .outputDirectory("") // optional; defaults to the working directory + .build()); + + System.out.println("Run " + polled.getRunId() + " status: " + polled.getStatus()); + if (polled.getStatus() == DetectRunStatus.SUCCESS) { + System.out.println("Outputs: " + polled.getOutput().size() + ", metrics: " + polled.getMetrics()); + } else if (polled.getStatus() == DetectRunStatus.FAILED) { + System.err.println("Run failed: " + polled.getMessage()); + } else { + System.out.println("Still running; poll later with getRun(" + polled.getRunId() + ")"); + } + } catch (SkyflowException e) { + System.err.println("Error during deidentifyFile:"); + e.printStackTrace(); + } + } +} diff --git a/flowvault/samples/src/main/java/com/example/detect/DeidentifyStringSample.java b/flowvault/samples/src/main/java/com/example/detect/DeidentifyStringSample.java new file mode 100644 index 00000000..b38ba42e --- /dev/null +++ b/flowvault/samples/src/main/java/com/example/detect/DeidentifyStringSample.java @@ -0,0 +1,94 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.DeidentificationType; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.DeidentifyStringResponse; +import com.skyflow.detect.Detect; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.DetectedEntity; +import com.skyflow.detect.Entity; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.ReturnEntitiesType; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.util.Arrays; +import java.util.Collections; + +/** + * De-identifies sensitive data in a string with the Detect V2 API, first with a stored + * configuration id and then with an inline configuration. + */ +public class DeidentifyStringSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + String text = "My name is John Doe, and my email is johndoe@acme.com."; + + // 1. Stored configuration, created in Studio or through the management API. + try { + DeidentifyStringResponse response = skyflowClient.detect().deidentifyString( + DeidentifyStringRequest.builder() + .text(text) + .configurationId("") // Replace with a Detect configuration id + .build()); + System.out.println("Processed text: " + response.getProcessedText()); + } catch (SkyflowException e) { + System.err.println("Error during deidentifyString (stored configuration):"); + e.printStackTrace(); + } + + // 2. Inline configuration, nothing to create beforehand. + DetectConfiguration configuration = DetectConfiguration.builder() + .detect(Detect.builder() + .entities(Arrays.asList( + Entity.builder() + .entityType(EntityType.NAME) + .deidentificationType(DeidentificationType.VAULT_TOKEN) + .destination("") // flowvault: token group that stores the value + .build(), + Entity.builder() + .entityType(EntityType.ALL) + .deidentificationType(DeidentificationType.ENTITY_UNIQUE_COUNTER) + .build())) + .skip(Collections.singletonList("Skyflow")) + .returnEntities(ReturnEntitiesType.EXCLUDE_SENSITIVE_DATA) + .build()) + .build(); + + try { + DeidentifyStringResponse response = skyflowClient.detect().deidentifyString( + DeidentifyStringRequest.builder() + .text(text) + .configuration(configuration) + .build()); + System.out.println("Processed text: " + response.getProcessedText()); + for (DetectedEntity entity : response.getEntities()) { + System.out.printf("%-16s %-18s [%d,%d] %s%n", + entity.getEntityType(), entity.getToken(), + entity.getLocation().getStartIndex(), entity.getLocation().getEndIndex(), + entity.getEntityScores()); + } + System.out.println("Metrics: " + response.getMetrics()); + } catch (SkyflowException e) { + System.err.println("Error during deidentifyString (inline configuration):"); + e.printStackTrace(); + } + } +} diff --git a/flowvault/samples/src/main/java/com/example/detect/GetRunSample.java b/flowvault/samples/src/main/java/com/example/detect/GetRunSample.java new file mode 100644 index 00000000..cc3e7667 --- /dev/null +++ b/flowvault/samples/src/main/java/com/example/detect/GetRunSample.java @@ -0,0 +1,62 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.GetRunRequest; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.io.File; +import java.nio.file.Files; +import java.util.Base64; + +/** + * Retrieves a Detect file run by id and, once it has succeeded, writes the base64 outputs to disk. + */ +public class GetRunSample { + public static void main(String[] args) throws Exception { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + try { + GetRunResponse run = skyflowClient.detect().getRun( + GetRunRequest.builder() + .runId("") // Replace with the run id returned by deidentifyFile + .build()); + + System.out.println("Run " + run.getRunId() + " status: " + run.getStatus()); + if (run.getStatus() == DetectRunStatus.SUCCESS) { + for (FileOutput output : run.getOutput()) { + String name = "processed-" + run.getRunId() + "-" + output.getProcessedFileType() + + "." + output.getProcessedFileExtension().name().toLowerCase(); + Files.write(new File(name).toPath(), Base64.getDecoder().decode(output.getProcessedFile())); + System.out.println("Wrote " + name); + } + System.out.println("Metrics: " + run.getMetrics()); + } else if (run.getStatus() == DetectRunStatus.FAILED) { + System.err.println("Run failed: " + run.getMessage()); + } else { + System.out.println("Run still pending, poll again later."); + } + } catch (SkyflowException e) { + System.err.println("Error during getRun:"); + e.printStackTrace(); + } + } +} diff --git a/flowvault/samples/src/main/java/com/example/detect/ReidentifyFileSample.java b/flowvault/samples/src/main/java/com/example/detect/ReidentifyFileSample.java new file mode 100644 index 00000000..587d58eb --- /dev/null +++ b/flowvault/samples/src/main/java/com/example/detect/ReidentifyFileSample.java @@ -0,0 +1,74 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.detect.ReidentifyFileResponse; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.io.File; +import java.nio.file.Files; +import java.util.Base64; +import java.util.Collections; + +/** + * Re-identifies the tokens in a text file with the Detect V2 API. The file is sent as base64 and + * the re-identified file is returned synchronously and written next to the input. + */ +public class ReidentifyFileSample { + public static void main(String[] args) throws Exception { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + File input = new File(""); // Replace with a file produced by deidentification + String base64 = Base64.getEncoder().encodeToString(Files.readAllBytes(input.toPath())); + + try { + ReidentifyFileResponse response = skyflowClient.detect().reidentifyFile( + ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64) + .value(base64) + .dataFormat(FileDataFormat.TXT) + // Optional: render one token group with a named redaction pattern instead of its plain value. + .redactionLevel(Collections.singletonList( + RedactionLevel.builder() + .tokenGroupName("") // Replace with a token group name + .redactionPattern("") // Replace with a redaction pattern name + .build())) + .build()); + + System.out.println("Status: " + response.getStatus()); + if (response.getStatus() == DetectRunStatus.SUCCESS) { + for (FileOutput output : response.getOutput()) { + String name = "reidentified-" + input.getName(); + Files.write(new File(input.getParentFile(), name).toPath(), + Base64.getDecoder().decode(output.getProcessedFile())); + System.out.println("Wrote " + name + " (" + output.getProcessedFileType() + ")"); + } + System.out.println("Metrics: " + response.getMetrics()); + } + } catch (SkyflowException e) { + System.err.println("Error during reidentifyFile:"); + e.printStackTrace(); + } + } +} diff --git a/flowvault/samples/src/main/java/com/example/detect/ReidentifyStringSample.java b/flowvault/samples/src/main/java/com/example/detect/ReidentifyStringSample.java new file mode 100644 index 00000000..508bcc6c --- /dev/null +++ b/flowvault/samples/src/main/java/com/example/detect/ReidentifyStringSample.java @@ -0,0 +1,59 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.detect.ReidentifyStringResponse; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.util.Collections; + +/** + * Re-identifies tokens in a string with the Detect V2 API. For flowvault vaults, redaction + * levels target a token group and apply a named redaction pattern. + */ +public class ReidentifyStringSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + try { + // Plain re-identification: every token is replaced by its original value. + ReidentifyStringResponse response = skyflowClient.detect().reidentifyString( + ReidentifyStringRequest.builder() + .text("My name is [NAME_1] and my email is [EMAIL_ADDRESS_1].") + .build()); + System.out.println("Processed text: " + response.getProcessedText()); + + // Targeted rendering: tokens from one token group are rendered with a named pattern. + ReidentifyStringResponse masked = skyflowClient.detect().reidentifyString( + ReidentifyStringRequest.builder() + .text("My name is [NAME_1].") + .redactionLevel(Collections.singletonList( + RedactionLevel.builder() + .tokenGroupName("") // Replace with a token group name + .redactionPattern("") // Replace with a redaction pattern name + .build())) + .build()); + System.out.println("Masked text: " + masked.getProcessedText()); + } catch (SkyflowException e) { + System.err.println("Error during reidentifyString:"); + e.printStackTrace(); + } + } +} diff --git a/flowvault/src/main/java/com/skyflow/Skyflow.java b/flowvault/src/main/java/com/skyflow/Skyflow.java index c2647824..b1955b63 100644 --- a/flowvault/src/main/java/com/skyflow/Skyflow.java +++ b/flowvault/src/main/java/com/skyflow/Skyflow.java @@ -3,7 +3,7 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.enums.LogLevel; -import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; @@ -12,6 +12,7 @@ import com.skyflow.utils.Utils; import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; +import com.skyflow.vault.controller.DetectController; import com.skyflow.vault.controller.VaultController; import java.util.LinkedHashMap; @@ -55,16 +56,38 @@ public Skyflow updateVaultConfig(VaultConfig vaultConfig) throws SkyflowExceptio } public VaultController vault() throws SkyflowException { - return resolveOrThrow(this.builder.vaultClientsMap, null, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, ErrorMessage.VaultIdNotInConfigList); + return resolveOrThrow(this.builder.vaultClientsMap, null, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); } public VaultController vault(String vaultId) throws SkyflowException { - return resolveOrThrow(this.builder.vaultClientsMap, vaultId, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, ErrorMessage.VaultIdNotInConfigList); + return resolveOrThrow(this.builder.vaultClientsMap, vaultId, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); + } + + /** + * Detect operations for the single configured vault. + * + * @return the detect controller + * @throws SkyflowException if no vault is configured + */ + public DetectController detect() throws SkyflowException { + return resolveOrThrow(this.builder.detectClientsMap, null, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); + } + + /** + * Detect operations for a specific configured vault. + * + * @param vaultId id of a configured vault + * @return the detect controller + * @throws SkyflowException if the vault is not configured + */ + public DetectController detect(String vaultId) throws SkyflowException { + return resolveOrThrow(this.builder.detectClientsMap, vaultId, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); } public static final class SkyflowClientBuilder extends BaseSkyflowClientBuilder { private final LinkedHashMap vaultClientsMap = new LinkedHashMap<>(); + private final LinkedHashMap detectClientsMap = new LinkedHashMap<>(); // Client-wide HTTP config. Resolution per vault, most specific first: // VaultConfig value -> the value set here -> SDK default (60s call timeout, 0 retries). // null here means "not set", so the SDK default applies to vaults that don't override it. @@ -89,6 +112,9 @@ protected void onVaultConfigAdded(VaultConfig vaultConfig) throws SkyflowExcepti this.writeTimeout, this.maxRetries, this.initialRetryDelayMillis, this.maxRetryDelayMillis); this.vaultClientsMap.put(vaultConfig.getVaultId(), controller); + DetectController detectController = new DetectController(vaultConfig, this.skyflowCredentials); + detectController.setCommonHttpConfig(this.timeout, this.maxRetries, this.initialRetryDelayMillis, this.maxRetryDelayMillis); + this.detectClientsMap.put(vaultConfig.getVaultId(), detectController); LogUtil.printInfoLog(Utils.parameterizedString(InfoLogs.VAULT_CONTROLLER_INITIALIZED.getLog(), vaultConfig.getVaultId())); } @@ -106,11 +132,20 @@ protected void onVaultConfigUpdated(VaultConfig updatedConfig) throws SkyflowExc updated.setCommonHttpConfig(this.timeout, this.connectTimeout, this.readTimeout, this.writeTimeout, this.maxRetries, this.initialRetryDelayMillis, this.maxRetryDelayMillis); + DetectController updatedDetect = this.detectClientsMap.get(updatedConfig.getVaultId()); + if (updatedDetect == null) { + updatedDetect = new DetectController(updatedConfig, this.skyflowCredentials); + this.detectClientsMap.put(updatedConfig.getVaultId(), updatedDetect); + } else { + updatedDetect.setVaultConfig(updatedConfig); + } + updatedDetect.setCommonHttpConfig(this.timeout, this.maxRetries, this.initialRetryDelayMillis, this.maxRetryDelayMillis); } @Override protected void onVaultConfigRemoved(String vaultId) throws SkyflowException { this.vaultClientsMap.remove(vaultId); + this.detectClientsMap.remove(vaultId); } @Override @@ -123,6 +158,9 @@ protected void onCredentialsUpdated(Credentials credentials) throws SkyflowExcep for (VaultController vault : this.vaultClientsMap.values()) { vault.setCommonCredentials(credentials); } + for (DetectController detect : this.detectClientsMap.values()) { + detect.setCommonCredentials(credentials); + } } @Override @@ -179,6 +217,10 @@ private void carryVaultOverrides(VaultConfig incoming) throws SkyflowException { if (controller != null) { controller.refreshVaultUrl(); } + DetectController detectController = this.detectClientsMap.get(incoming.getVaultId()); + if (detectController != null) { + detectController.refreshVaultUrl(); + } } } @@ -294,6 +336,10 @@ private void propagateHttpConfig() { this.writeTimeout, this.maxRetries, this.initialRetryDelayMillis, this.maxRetryDelayMillis); } + for (DetectController detect : this.detectClientsMap.values()) { + detect.setCommonHttpConfig(this.timeout, this.maxRetries, this.initialRetryDelayMillis, + this.maxRetryDelayMillis); + } } public Skyflow build() { diff --git a/flowvault/src/main/java/com/skyflow/VaultClient.java b/flowvault/src/main/java/com/skyflow/VaultClient.java index 93a677e0..8a7264c9 100644 --- a/flowvault/src/main/java/com/skyflow/VaultClient.java +++ b/flowvault/src/main/java/com/skyflow/VaultClient.java @@ -1,5 +1,7 @@ package com.skyflow; +import java.util.concurrent.TimeUnit; + import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.errors.SkyflowException; @@ -9,8 +11,6 @@ import com.skyflow.utils.SkyflowRetryInterceptor; import com.skyflow.utils.Utils; -import java.util.concurrent.TimeUnit; - import okhttp3.ConnectionPool; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -63,6 +63,7 @@ private static int resolveInt(Integer vaultLevel, Integer clientLevel, int defau if (vaultLevel != null) { return vaultLevel; } + return clientLevel != null ? clientLevel : defaultValue; } diff --git a/flowvault/src/main/java/com/skyflow/config/VaultConfig.java b/flowvault/src/main/java/com/skyflow/config/VaultConfig.java index 3369abc7..0de26f42 100644 --- a/flowvault/src/main/java/com/skyflow/config/VaultConfig.java +++ b/flowvault/src/main/java/com/skyflow/config/VaultConfig.java @@ -37,6 +37,7 @@ public VaultConfig() { } public String getVaultUrl() { + return vaultUrl; } diff --git a/flowvault/src/main/java/com/skyflow/errors/ErrorMessage.java b/flowvault/src/main/java/com/skyflow/errors/ErrorMessage.java new file mode 100644 index 00000000..d2c92a4c --- /dev/null +++ b/flowvault/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -0,0 +1,74 @@ +package com.skyflow.errors; + +import com.skyflow.utils.Constants; + +/** + * Validation messages specific to the flowvault SDK. Messages shared by every SDK live in + * {@link BaseErrorMessage} in common; this enum holds only what common and skyvault do not use. + */ +public enum ErrorMessage { + // Vault config + EmptyVaultUrl("%s0 Initialization failed. Vault URL is empty. Specify a valid vault URL."), + InvalidVaultUrlFormat("%s0 Initialization failed. Vault URL must start with 'https://'."), + EitherVaultUrlOrClusterIdRequired("%s0 Initialization failed. Specify either 'clusterId' or 'vaultURL'."), + // Insert / upsert + TableSpecifiedInRequestAndRecordObject("%s0 Validation error. Table name cannot be specified at both the request and record levels. Please specify the table name in only one place."), + TableNotSpecifiedInRequestAndRecordObject("%s0 Validation error. Table name is missing. Table name should be specified at one place either at the request level or record level. Please specify the table name at one place."), + UpsertTableRequestAtRecordLevel("%s0 Validation error. Table name should be present at each record level when upsert is present at record level."), + UpsertTableRequestAtRequestLevel("%s0 Validation error. Upsert should be present at each record level when table name is present at record level."), + EmptyRecords("%s0 Validation error. 'records' can't be empty. Specify records."), + EmptyKeyInRecords("%s0 Validation error. Invalid key in data in records. Specify a valid key."), + EmptyValueInRecords("%s0 Validation error. Invalid value in records. Specify a valid value."), + RecordsKeyError("%s0 Validation error. 'records' key is missing from the payload. Specify a 'records' key."), + InvalidUpsertUpdateType("%s0 Validation error. Invalid upsert updateType. Specify either 'UPDATE' or 'REPLACE'."), + EmptyUpsertValues("%s0 Validation error. Upsert column values can't be empty. Specify at least one upsert column."), + RecordSizeExceedError("%s0 Maximum number of records exceeded. The limit is 100000."), + InvalidRecord("%s0 Validation error. InsertRecord object in the list is invalid. Specify a valid InsertRecord object."), + BothSingleTableFieldsAndRecordsSpecified("%s0 Validation error. Both single-table lookup fields ('table', 'ids', 'fields', 'uniqueValues', 'columnRedactions') and 'records' can't be specified. Either specify single-table fields or 'records'."), + // Detokenize / delete tokens + EmptyValues("%s0 Validation error. 'values' can't be empty. Specify values."), + EmptyValueInValues("%s0 Validation error. Invalid value in values. Specify a valid value."), + EmptyValueInTokens("%s0 Validation error. Invalid value in tokens. Specify a valid value."), + TokensSizeExceedError("%s0 Maximum number of tokens exceeded. The limit is 100000."), + DeleteTokensRequestNull("%s0 Validation error. DeleteTokensRequest object is null. Specify a valid DeleteTokensRequest object."), + EmptyDeleteTokensData("%s0 Validation error. Tokens list is empty. Specify at least one token to delete."), + EmptyTokenInDeleteTokensData("%s0 Validation error. Invalid token in delete tokens request. Specify a valid token."), + DeleteTokensSizeExceedError("%s0 Maximum number of tokens exceeded. The limit is 100000."), + NullTokenGroupRedactions("%s0 Validation error. TokenGroupRedaction in the list is null. Specify a valid TokenGroupRedactions object."), + NullRedactionInTokenGroup("%s0 Validation error. Redaction in TokenGroupRedactions is null or empty. Specify a valid redaction."), + NullTokenGroupNameInTokenGroup("%s0 Validation error. TokenGroupName in TokenGroupRedactions is null or empty. Specify a valid tokenGroupName."), + // Get / update + IdsOrUniqueValuesKeyError("%s0 Validation error. 'ids' or 'uniqueValues' key is missing from the payload. Specify ids or uniqueValues in payload."), + BothIdsAndUniqueValuesSpecified("%s0 Validation error. Both Skyflow IDs and unique values can't be specified. Either specify Skyflow IDs or unique values."), + EmptyUniqueValues("%s0 Validation error. 'uniqueValues' can't be empty. Specify at least one unique value."), + EmptyUniqueValueInUniqueValues("%s0 Validation error. Invalid unique value in 'uniqueValues'. Specify a valid unique value."), + NullColumnRedactions("%s0 Validation error. Column redaction object can not be null. Specify a valid column redaction object."), + NullColumnNameInColumnRedaction("%s0 Validation error. Column name can not be null or empty in column redaction. Specify a valid column name."), + NullRedactionInColumnRedaction("%s0 Validation error. Redaction can not be null or empty in column redaction. Specify a valid redaction."), + NullGetRecordRequest("%s0 Validation error. Record in 'records' is null. Specify a valid record."), + UpdateRecordNull("%s0 Validation error. UpdateRequestRecord object in the list is null. Specify a valid UpdateRequestRecord object."), + RecordSkyflowIdKeyError("%s0 Validation error. 'skyflowId' key is missing from the record. Specify a 'skyflowId' key."), + EmptySkyflowIdInRecord("%s0 Validation error. 'skyflowId' can't be empty in the record. Specify a valid skyflow ID."), + // Tokenize + EmptyTokenizeData("%s0 Validation error. Tokenize data is empty. Specify at least one tokenize record."), + TokenizeRecordNull("%s0 Validation error. TokenizeRecord in the list is null. Specify a valid TokenizeRecord object."), + InvalidBulkTokenizeRecordType("%s0 Validation error. Record in the list must be of type BulkTokenizeRequestRecord. Specify a valid BulkTokenizeRequestRecord object."), + EmptyValueInTokenizeRecord("%s0 Validation error. Value in TokenizeRecord is null or empty. Specify a valid value."), + EmptyTokenGroupNamesInTokenizeRecord("%s0 Validation error. TokenGroupNames in TokenizeRecord is null or empty. Specify at least one token group name."), + EmptyTokenGroupNameInTokenizeRecord("%s0 Validation error. Token group name in TokenizeRecord is null or empty. Specify a valid token group name."), + TokenizeDataSizeExceedError("%s0 Maximum number of tokenize records exceeded. The limit is 100000."), + MissingIndexInBulkTokenizeRecord("%s0 Validation error. Index in BulkTokenizeRequestRecord is null. Specify an index for every record."), + DuplicateIndexInBulkTokenizeRecord("%s0 Validation error. Duplicate index in BulkTokenizeRequestRecord. Specify a unique index for every record."), + // Detect (flowvault only) + ; + + private final String message; + + ErrorMessage(String message) { + this.message = message.replace("%s0", Constants.SDK_PREFIX); + } + + public String getMessage() { + return message; + } +} diff --git a/flowvault/src/main/java/com/skyflow/utils/validations/Validations.java b/flowvault/src/main/java/com/skyflow/utils/validations/Validations.java index 084b01d7..257685f1 100644 --- a/flowvault/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/flowvault/src/main/java/com/skyflow/utils/validations/Validations.java @@ -5,6 +5,7 @@ import com.skyflow.enums.InterfaceName; import com.skyflow.generated.rest.types.FlowEnumUpdateType; import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; @@ -42,38 +43,38 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx if (nonNullMembers > 1) { LogUtil.printErrorLog(ErrorLogs.MULTIPLE_TOKEN_GENERATION_MEANS_PASSED.getLog()); throw new SkyflowException( - ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MultipleTokenGenerationMeansPassed.getMessage() + ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.MultipleTokenGenerationMeansPassed.getMessage() ); } else if (nonNullMembers < 1) { LogUtil.printErrorLog(ErrorLogs.NO_TOKEN_GENERATION_MEANS_PASSED.getLog()); throw new SkyflowException( - ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.NoTokenGenerationMeansPassed.getMessage() + ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.NoTokenGenerationMeansPassed.getMessage() ); } else if (path != null && path.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_CREDENTIALS_PATH.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentialFilePath.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyCredentialFilePath.getMessage()); } else if (credentialsString != null && credentialsString.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_CREDENTIALS_STRING.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentialsString.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyCredentialsString.getMessage()); } else if (token != null && token.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_TOKEN_VALUE.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyToken.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyToken.getMessage()); } else if (apiKey != null) { if (apiKey.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_API_KEY_VALUE.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyApikey.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyApikey.getMessage()); } else { Pattern pattern = Pattern.compile(Constants.API_KEY_REGEX); Matcher matcher = pattern.matcher(apiKey); if (!matcher.matches()) { LogUtil.printErrorLog(ErrorLogs.INVALID_API_KEY.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidApikey.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidApikey.getMessage()); } } } else if (roles != null) { if (roles.isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_ROLES.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRoles.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyRoles.getMessage()); } else { for (int index = 0; index < roles.size(); index++) { String role = roles.get(index); @@ -81,7 +82,7 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_ROLE_IN_ROLES.getLog(), Integer.toString(index) )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRoleInRoles.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyRoleInRoles.getMessage()); } } } @@ -91,13 +92,13 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx String ctxStr = (String) context; if (ctxStr.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_OR_NULL_CONTEXT.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyContext.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyContext.getMessage()); } } else if (context instanceof Map) { Map ctxMap = (Map) context; if (ctxMap.isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_OR_NULL_CONTEXT.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyContext.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyContext.getMessage()); } Pattern ctxKeyPattern = Pattern.compile(Constants.CONTEXT_KEY_REGEX); for (Object key : ctxMap.keySet()) { @@ -106,12 +107,12 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.INVALID_CONTEXT_MAP_KEY.getLog(), keyStr)); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - Utils.parameterizedString(ErrorMessage.InvalidContextMapKey.getMessage(), keyStr)); + Utils.parameterizedString(BaseErrorMessage.InvalidContextMapKey.getMessage(), keyStr)); } } } else { LogUtil.printErrorLog(ErrorLogs.INVALID_CONTEXT_TYPE.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidContextType.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidContextType.getMessage()); } } } @@ -120,7 +121,7 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx public static void validateVaultConfiguration(VaultConfig vaultConfig) throws SkyflowException { if (vaultConfig == null) { LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_IS_NULL.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.NullVaultConfig.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.NullVaultConfig.getMessage()); } String vaultId = vaultConfig.getVaultId(); String clusterId = vaultConfig.getClusterId(); @@ -129,10 +130,10 @@ public static void validateVaultConfiguration(VaultConfig vaultConfig) throws Sk if (vaultId == null) { LogUtil.printErrorLog(ErrorLogs.VAULT_ID_IS_REQUIRED.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidVaultId.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InvalidVaultId.getMessage()); } else if (vaultId.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_VAULT_ID.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyVaultId.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyVaultId.getMessage()); } else if (credentials != null) { validateCredentials(credentials); } @@ -153,7 +154,7 @@ public static void validateVaultConfiguration(VaultConfig vaultConfig) throws Sk throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EitherVaultUrlOrClusterIdRequired.getMessage()); } else if (clusterId.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_CLUSTER_ID.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyClusterId.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyClusterId.getMessage()); } } } @@ -164,7 +165,7 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.INSERT_REQUEST_NULL.getLog(), InterfaceName.INSERT.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InsertRequestNull.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.InsertRequestNull.getMessage()); } List records = insertRequest.getRecords(); if (records == null) { @@ -225,14 +226,14 @@ private static void validateInsertRecordTokens(Map tokens) throw LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.INSERT.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokens.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyTokens.getMessage()); } for (String key : tokens.keySet()) { if (key == null || key.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_KEY_IN_TOKENS.getLog(), InterfaceName.INSERT.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInTokens.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyKeyInTokens.getMessage()); } Object value = tokens.get(key); if (value == null || value.toString().trim().isEmpty()) { @@ -332,14 +333,14 @@ public static void validateDetokenizeRequest(DetokenizeRequest request) throws S LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.DETOKENIZE_REQUEST_NULL.getLog(), InterfaceName.DETOKENIZE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.DetokenizeRequestNull.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.DetokenizeRequestNull.getMessage()); } List tokens = request.getTokens(); if (tokens == null || tokens.isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_DETOKENIZE_DATA.getLog(), InterfaceName.DETOKENIZE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyDetokenizeData.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyDetokenizeData.getMessage()); } for (int index = 0; index < tokens.size(); index++) { @@ -349,7 +350,7 @@ public static void validateDetokenizeRequest(DetokenizeRequest request) throws S ErrorLogs.EMPTY_OR_NULL_TOKEN_IN_DETOKENIZE_DATA.getLog(), InterfaceName.DETOKENIZE.getName(), String.valueOf(index))); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokenInDetokenizeData.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyTokenInDetokenizeData.getMessage()); } } @@ -418,7 +419,7 @@ public static void validateDeleteRequest(DeleteRequest deleteRequest) throws Sky LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.DELETE_REQUEST_NULL.getLog(), InterfaceName.DELETE_RECORDS.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.DeleteRequestNull.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.DeleteRequestNull.getMessage()); } validateTableRequired(deleteRequest.getTableName(), InterfaceName.DELETE_RECORDS); validateIdsOrUniqueValues(deleteRequest.getSkyflowIds(), deleteRequest.getUniqueValues(), InterfaceName.DELETE_RECORDS); @@ -458,19 +459,19 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.UPDATE_REQUEST_NULL.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.UpdateRequestNull.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.UpdateRequestNull.getMessage()); } String tableName = updateRequest.getTableName(); if (tableName == null) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.TableKeyError.getMessage()); } else if (tableName.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyTable.getMessage()); } List records = updateRequest.getRecords(); @@ -532,14 +533,14 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokens.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyTokens.getMessage()); } for (String key : tokens.keySet()) { if (key == null || key.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_KEY_IN_TOKENS.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInTokens.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyKeyInTokens.getMessage()); } Object value = tokens.get(key); if (value == null || value.toString().trim().isEmpty()) { @@ -559,7 +560,7 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.GET_REQUEST_NULL.getLog(), InterfaceName.GET.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.GetRequestNull.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.GetRequestNull.getMessage()); } boolean hasSingleTableFields = hasText(getRequest.getTableName()) @@ -603,12 +604,12 @@ private static void validateTableRequired(String table, InterfaceName interfaceN LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TABLE_IS_REQUIRED.getLog(), interfaceName.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.TableKeyError.getMessage()); } else if (table.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TABLE_NAME.getLog(), interfaceName.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyTable.getMessage()); } } @@ -638,7 +639,7 @@ private static void validateIdsOrUniqueValues(List ids, List fields) throws SkyflowException LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_FIELDS.getLog(), InterfaceName.GET.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFields.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyFields.getMessage()); } for (int index = 0; index < fields.size(); index++) { String field = fields.get(index); @@ -671,7 +672,7 @@ private static void validateFields(List fields) throws SkyflowException LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_FIELD_IN_FIELDS.getLog(), InterfaceName.GET.getName(), String.valueOf(index) )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFieldInFields.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.EmptyFieldInFields.getMessage()); } } } @@ -711,7 +712,7 @@ public static void validateBulkTokenizeRequest(BulkTokenizeRequest request) thro LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENIZE_REQUEST_NULL.getLog(), InterfaceName.TOKENIZE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TokenizeRequestNull.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), BaseErrorMessage.TokenizeRequestNull.getMessage()); } List records = request.getRecords(); if (records == null || records.isEmpty()) { diff --git a/flowvault/src/main/java/com/skyflow/vault/controller/DetectController.java b/flowvault/src/main/java/com/skyflow/vault/controller/DetectController.java new file mode 100644 index 00000000..573eb349 --- /dev/null +++ b/flowvault/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -0,0 +1,71 @@ +package com.skyflow.vault.controller; + +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Utils; + +/** + * Skyflow Detect operations for a flowvault vault, returned by {@code Skyflow.detect()} and + * {@code Skyflow.detect(vaultId)}. The shared Detect V2 methods are inherited from + * {@link BaseDetectController} and shared with the skyvault SDK; this class only supplies the + * flowvault URL rules, SDK metrics and the vault-level timeout and retry overrides from + * {@link VaultConfig}. + */ +public final class DetectController extends BaseDetectController { + private static final int DEFAULT_TIMEOUT_SECONDS = 60; + private static final int DEFAULT_MAX_RETRIES = 0; + private static final long DEFAULT_INITIAL_RETRY_DELAY_MILLIS = 500L; + private static final long DEFAULT_MAX_RETRY_DELAY_MILLIS = 2000L; + + public DetectController(VaultConfig vaultConfig, Credentials credentials) { + super(vaultConfig, credentials); + } + + /** Same precedence as the vault controller: environment variable, explicit vaultUrl, then cluster id and env. */ + @Override + protected String resolveVaultUrl() throws SkyflowException { + String vaultUrl = Utils.getEnvVaultUrl(); + if (vaultUrl == null || vaultUrl.isEmpty()) { + vaultUrl = getVaultConfig().getVaultUrl(); + } + if (vaultUrl == null || vaultUrl.isEmpty()) { + vaultUrl = Utils.getVaultUrl(getVaultConfig().getClusterId(), getVaultConfig().getEnv()); + } + return vaultUrl; + } + + @Override + protected String getSdkMetrics() { + return Utils.getMetrics().toString(); + } + + @Override + protected Integer effectiveTimeoutSeconds() { + return firstNonNull(getVaultConfig().getTimeout(), super.effectiveTimeoutSeconds(), DEFAULT_TIMEOUT_SECONDS); + } + + @Override + protected Integer effectiveMaxRetries() { + return firstNonNull(getVaultConfig().getMaxRetries(), super.effectiveMaxRetries(), DEFAULT_MAX_RETRIES); + } + + @Override + protected Long effectiveInitialRetryDelayMillis() { + return firstNonNull(getVaultConfig().getInitialRetryDelayMillis(), super.effectiveInitialRetryDelayMillis(), + DEFAULT_INITIAL_RETRY_DELAY_MILLIS); + } + + @Override + protected Long effectiveMaxRetryDelayMillis() { + return firstNonNull(getVaultConfig().getMaxRetryDelayMillis(), super.effectiveMaxRetryDelayMillis(), + DEFAULT_MAX_RETRY_DELAY_MILLIS); + } + + private static T firstNonNull(T vaultLevel, T clientLevel, T defaultValue) { + if (vaultLevel != null) { + return vaultLevel; + } + return clientLevel != null ? clientLevel : defaultValue; + } +} diff --git a/flowvault/src/test/java/com/skyflow/utils/validations/ValidationsTests.java b/flowvault/src/test/java/com/skyflow/utils/validations/ValidationsTests.java index f900c03a..fb40b63c 100644 --- a/flowvault/src/test/java/com/skyflow/utils/validations/ValidationsTests.java +++ b/flowvault/src/test/java/com/skyflow/utils/validations/ValidationsTests.java @@ -15,6 +15,7 @@ import com.skyflow.config.VaultConfig; import com.skyflow.enums.Env; import com.skyflow.enums.UpdateType; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.utils.Constants; @@ -232,7 +233,7 @@ public void testValidateVaultConfiguration_nullRequest() { Validations.validateVaultConfiguration(null); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.NullVaultConfig.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.NullVaultConfig.getMessage(), e.getMessage()); } } @@ -582,7 +583,7 @@ public void testValidateInsertRequest_emptyTokensMapThrows() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyTokens.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyTokens.getMessage(), e.getMessage()); } } @@ -597,7 +598,7 @@ public void testValidateInsertRequest_nullKeyInTokensThrows() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); } } @@ -612,7 +613,7 @@ public void testValidateInsertRequest_blankKeyInTokensThrows() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); } } @@ -1610,7 +1611,7 @@ public void testValidateDeleteRequest_nullRequestThrows() { Validations.validateDeleteRequest(null); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.DeleteRequestNull.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.DeleteRequestNull.getMessage(), e.getMessage()); } } @@ -1621,7 +1622,7 @@ public void testValidateDeleteRequest_nullTableThrows() { Validations.validateDeleteRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.TableKeyError.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.TableKeyError.getMessage(), e.getMessage()); } } @@ -1632,7 +1633,7 @@ public void testValidateDeleteRequest_blankTableThrows() { Validations.validateDeleteRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyTable.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyTable.getMessage(), e.getMessage()); } } @@ -1671,7 +1672,7 @@ public void testValidateDeleteRequest_blankIdInIdsThrows() { Validations.validateDeleteRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyIdInIds.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyIdInIds.getMessage(), e.getMessage()); } } @@ -1722,7 +1723,7 @@ public void testValidateUpdateRequest_nullRequestThrows() { Validations.validateUpdateRequest(null); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.UpdateRequestNull.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.UpdateRequestNull.getMessage(), e.getMessage()); } } @@ -1734,7 +1735,7 @@ public void testValidateUpdateRequest_nullTableNameThrows() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.TableKeyError.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.TableKeyError.getMessage(), e.getMessage()); } } @@ -1746,7 +1747,7 @@ public void testValidateUpdateRequest_blankTableNameThrows() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyTable.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyTable.getMessage(), e.getMessage()); } } @@ -1845,7 +1846,7 @@ public void testValidateUpdateRequest_emptyTokensMapThrows() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyTokens.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyTokens.getMessage(), e.getMessage()); } } @@ -1859,7 +1860,7 @@ public void testValidateUpdateRequest_blankKeyInTokensThrows() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); } } @@ -1917,7 +1918,7 @@ public void testValidateGetRequest_nullRequestThrows() { Validations.validateGetRequest(null); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.GetRequestNull.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.GetRequestNull.getMessage(), e.getMessage()); } } @@ -1957,7 +1958,7 @@ public void testValidateGetRequest_nullTableThrows() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.TableKeyError.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.TableKeyError.getMessage(), e.getMessage()); } } @@ -1968,7 +1969,7 @@ public void testValidateGetRequest_blankTableThrows() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyTable.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyTable.getMessage(), e.getMessage()); } } @@ -2010,7 +2011,7 @@ public void testValidateGetRequest_blankIdInIdsThrows() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyIdInIds.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyIdInIds.getMessage(), e.getMessage()); } } @@ -2039,7 +2040,7 @@ public void testValidateGetRequest_emptyFieldsThrows() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyFields.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyFields.getMessage(), e.getMessage()); } } @@ -2054,7 +2055,7 @@ public void testValidateGetRequest_blankFieldInFieldsThrows() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyFieldInFields.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.EmptyFieldInFields.getMessage(), e.getMessage()); } } @@ -2163,7 +2164,7 @@ public void testValidateGetRequest_multiTableRecordMissingTableThrows() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.TableKeyError.getMessage(), e.getMessage()); + Assert.assertEquals(BaseErrorMessage.TableKeyError.getMessage(), e.getMessage()); } } } diff --git a/flowvault/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java b/flowvault/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java new file mode 100644 index 00000000..0af983c8 --- /dev/null +++ b/flowvault/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java @@ -0,0 +1,633 @@ +package com.skyflow.vault.controller; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.CheckGuardrailsResponse; +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DeidentificationType; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyFileResponse; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.DeidentifyStringResponse; +import com.skyflow.detect.Detect; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.Entity; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.GetRunRequest; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.GuardrailsValidation; +import com.skyflow.detect.PollOptions; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.detect.ReidentifyFileResponse; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.detect.ReidentifyStringResponse; +import com.skyflow.enums.Env; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; +import java.util.Base64; + +import java.util.Arrays; +import java.util.Collections; + +public class DetectControllerTests { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private static VaultConfig vaultConfig(String vaultId) { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultId); + config.setClusterId("cluster123"); + config.setEnv(Env.PROD); + return config; + } + + @Test + public void detectAccessorResolvesConfiguredVaults() throws SkyflowException { + Skyflow client = Skyflow.builder() + .addVaultConfig(vaultConfig("vault-a")) + .addVaultConfig(vaultConfig("vault-b")) + .build(); + Assert.assertNotNull(client.detect()); + Assert.assertSame(client.detect(), client.detect("vault-a")); + Assert.assertNotSame(client.detect("vault-a"), client.detect("vault-b")); + try { + client.detect("vault-c"); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void detectAccessorFollowsVaultConfigRemoval() throws SkyflowException { + Skyflow client = Skyflow.builder().addVaultConfig(vaultConfig("vault-a")).build(); + client.removeVaultConfig("vault-a"); + try { + client.detect(); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void deidentifyStringValidatesBeforeResolvingCredentials() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), (Credentials) null); + try { + controller.deidentifyString(DeidentifyStringRequest.builder().text(" ").configurationId("cfg").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.InvalidTextInDeidentifyString.getMessage(), e.getMessage()); + } + } + + @Test + public void reidentifyStringValidatesBeforeResolvingCredentials() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), (Credentials) null); + try { + controller.reidentifyString(ReidentifyStringRequest.builder().text(" ").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.InvalidTextInReidentifyString.getMessage(), e.getMessage()); + } + } + + /** + * Null credentials would make the SDK fall back to SKYFLOW_CREDENTIALS from the environment or a + * .env file, which CI provides, so the outcome would depend on the machine. An explicitly empty + * {@link Credentials} is rejected by validation the same way everywhere, before any network call. + */ + @Test + public void missingCredentialsSurfaceAsSkyflowExceptionWithoutNetworkCall() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), emptyCredentials()); + try { + controller.reidentifyString(ReidentifyStringRequest.builder().text("[NAME_1]").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); + } + } + + /** Credentials with no path, string, token or API key set. */ + private static Credentials emptyCredentials() { + return new Credentials(); + } + + // ─── reidentifyFile (flowvault only) ────────────────────────────────────── + + /** API-key credentials resolve without a token exchange, so the only network call is the Detect request. */ + private static Credentials apiKeyCredentials() { + Credentials credentials = new Credentials(); + credentials.setApiKey("sky-abcde-0123456789abcdef0123456789abcdef"); + return credentials; + } + + private static DetectController controllerFor(MockWebServer server) { + VaultConfig config = vaultConfig("vault-1"); + config.setVaultUrl(server.url("").toString()); + DetectController controller = new DetectController(config, apiKeyCredentials()); + controller.setCommonHttpConfig(null, 0, null, null); + return controller; + } + + @Test + public void reidentifyFileValidatesBeforeResolvingCredentials() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), (Credentials) null); + ReidentifyFileRequest[] bad = { + null, + ReidentifyFileRequest.builder().value("Zm9v").build(), + ReidentifyFileRequest.builder().dataSource(DataSourceType.BASE64).value(" ").build(), + }; + BaseErrorMessage[] expected = { + BaseErrorMessage.ReidentifyFileRequestNull, + BaseErrorMessage.InvalidDataSourceInReidentifyFile, + BaseErrorMessage.InvalidValueInReidentifyFile, + }; + for (int i = 0; i < bad.length; i++) { + try { + controller.reidentifyFile(bad[i]); + Assert.fail("expected SkyflowException for case " + i); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(expected[i].getMessage(), e.getMessage()); + } + } + } + + @Test + public void reidentifyFileMissingCredentialsSurfaceWithoutNetworkCall() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), emptyCredentials()); + try { + controller.reidentifyFile(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); + } + } + + @Test + public void reidentifyFileSendsScopedRequestAndMapsResponse() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") + .setBody("{\"status\":\"SUCCESS\",\"outputType\":\"BASE64\"," + + "\"output\":[{\"processedFile\":\"SGVsbG8=\",\"processedFileType\":\"REIDENTIFIED_FILE\"," + + "\"processedFileExtension\":\"txt\"}]," + + "\"metrics\":{\"size\":0.5,\"wordCount\":3,\"characterCount\":12}}")); + + ReidentifyFileResponse response = controllerFor(server).reidentifyFile(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64) + .value("W05BTUVfMV0=") + .dataFormat(FileDataFormat.TXT) + .redactionLevel(Arrays.asList( + RedactionLevel.builder().tokenGroupName("names").redactionPattern("mask").build())) + .build()); + + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(DataSourceType.BASE64, response.getOutputType()); + Assert.assertEquals(1, response.getOutput().size()); + Assert.assertEquals("SGVsbG8=", response.getOutput().get(0).getProcessedFile()); + Assert.assertEquals("REIDENTIFIED_FILE", response.getOutput().get(0).getProcessedFileType()); + Assert.assertEquals(FileDataFormat.TXT, response.getOutput().get(0).getProcessedFileExtension()); + Assert.assertEquals(Integer.valueOf(3), response.getMetrics().getWordCount()); + + RecordedRequest recorded = server.takeRequest(); + Assert.assertEquals("POST", recorded.getMethod()); + Assert.assertEquals("/v2/detect/reidentify/file", recorded.getPath()); + Assert.assertEquals("Bearer sky-abcde-0123456789abcdef0123456789abcdef", recorded.getHeader("Authorization")); + Assert.assertNotNull(recorded.getHeader("sky-metadata")); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"dataSource\":\"BASE64\"")); + Assert.assertTrue(body, body.contains("\"value\":\"W05BTUVfMV0=\"")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(body, body.contains("\"dataFormat\":\"txt\"")); + Assert.assertTrue(body, body.contains("\"tokenGroupName\":\"names\"")); + Assert.assertTrue(body, body.contains("\"redactionPattern\":\"mask\"")); + } finally { + server.shutdown(); + } + } + + @Test + public void reidentifyFileToleratesSparseAndUnknownResponseValues() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"SOMETHING_NEW\"}")); + ReidentifyFileResponse response = controllerFor(server).reidentifyFile(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.SKYFLOW_ID).value("rec-1").build()); + Assert.assertEquals(DetectRunStatus.UNKNOWN, response.getStatus()); + Assert.assertNull(response.getOutputType()); + Assert.assertTrue(response.getOutput().isEmpty()); + Assert.assertNull(response.getMetrics()); + String body = server.takeRequest().getBody().readUtf8(); + Assert.assertFalse(body, body.contains("dataFormat")); + Assert.assertFalse(body, body.contains("redactionLevel")); + } finally { + server.shutdown(); + } + } + + @Test + public void reidentifyFileMapsApiErrors() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(400).setHeader("x-request-id", "req-9") + .setBody("{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"unsupported format\"," + + "\"http_status\":\"Bad Request\",\"details\":[]}}")); + try { + controllerFor(server).reidentifyFile(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.PRESIGNED_URL).value("https://example.com/f").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(400, e.getHttpCode()); + Assert.assertEquals("unsupported format", e.getMessage()); + Assert.assertEquals("req-9", e.getRequestId()); + Assert.assertEquals(Integer.valueOf(3), e.getGrpcCode()); + } + } finally { + server.shutdown(); + } + } + + // ─── inherited Detect V2 methods, exercised through the flowvault controller ── + // These prove the flowvault wiring (vault URL from VaultConfig, API-key credentials, + // flowvault SDK metrics header) end to end, not just the shared base logic. + + private static final String API_KEY = "sky-abcde-0123456789abcdef0123456789abcdef"; + + private static void assertCommonHeaders(RecordedRequest recorded, String method, String path) { + Assert.assertEquals(method, recorded.getMethod()); + Assert.assertEquals(path, recorded.getPath()); + Assert.assertEquals("Bearer " + API_KEY, recorded.getHeader("Authorization")); + String metrics = recorded.getHeader("sky-metadata"); + Assert.assertNotNull(metrics); + Assert.assertTrue(metrics, metrics.contains("skyflow-flowvault-java@")); + } + + @Test + public void deidentifyStringRoundTripWithStoredConfiguration() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") + .setBody("{\"processedText\":\"My name is [NAME_1].\"," + + "\"entities\":[{\"token\":\"NAME_1\",\"value\":\"John Doe\",\"entityType\":\"NAME\"," + + "\"location\":{\"startIndex\":11,\"endIndex\":19,\"startIndexProcessed\":11,\"endIndexProcessed\":19}," + + "\"entityScores\":{\"NAME\":0.98}}]," + + "\"metrics\":{\"wordCount\":4,\"characterCount\":20}}")); + + DeidentifyStringResponse response = controllerFor(server).deidentifyString(DeidentifyStringRequest.builder() + .text("My name is John Doe.").configurationId("cfg-123").build()); + + Assert.assertEquals("My name is [NAME_1].", response.getProcessedText()); + Assert.assertEquals(1, response.getEntities().size()); + Assert.assertEquals("NAME_1", response.getEntities().get(0).getToken()); + Assert.assertEquals("John Doe", response.getEntities().get(0).getValue()); + Assert.assertEquals("NAME", response.getEntities().get(0).getEntityType()); + Assert.assertEquals(Integer.valueOf(11), response.getEntities().get(0).getLocation().getStartIndex()); + Assert.assertEquals(Integer.valueOf(19), response.getEntities().get(0).getLocation().getEndIndexProcessed()); + Assert.assertEquals(0.98, response.getEntities().get(0).getEntityScores().get("NAME"), 1e-9); + Assert.assertEquals(Integer.valueOf(4), response.getMetrics().getWordCount()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "POST", "/v2/detect/deidentify/string"); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"text\":\"My name is John Doe.\"")); + Assert.assertTrue(body, body.contains("\"configurationId\":\"cfg-123\"")); + Assert.assertFalse(body, body.contains("\"configuration\":")); + } finally { + server.shutdown(); + } + } + + @Test + public void deidentifyStringRoundTripWithInlineConfigurationScopedToVault() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"processedText\":\"[NAME_1]\"}")); + + DeidentifyStringResponse response = controllerFor(server).deidentifyString(DeidentifyStringRequest.builder() + .text("John") + .configuration(DetectConfiguration.builder() + .detect(Detect.builder().entities(Collections.singletonList( + Entity.builder().entityType(EntityType.NAME) + .deidentificationType(DeidentificationType.VAULT_TOKEN) + .destination("names").build())).build()) + .build()) + .build()); + + Assert.assertEquals("[NAME_1]", response.getProcessedText()); + Assert.assertTrue(response.getEntities().isEmpty()); + Assert.assertNull(response.getMetrics()); + + String body = server.takeRequest().getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"configuration\":{")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); // injected by the controller + Assert.assertTrue(body, body.contains("\"entityType\":\"NAME\"")); + Assert.assertTrue(body, body.contains("\"deidentificationType\":\"VAULT_TOKEN\"")); + Assert.assertTrue(body, body.contains("\"destination\":\"names\"")); + Assert.assertFalse(body, body.contains("configurationId")); + } finally { + server.shutdown(); + } + } + + @Test + public void reidentifyStringRoundTrip() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"processedText\":\"My name is J**n D*e.\",\"metrics\":{\"wordCount\":5}}")); + + ReidentifyStringResponse response = controllerFor(server).reidentifyString(ReidentifyStringRequest.builder() + .text("My name is [NAME_1].") + .redactionLevel(Collections.singletonList( + RedactionLevel.builder().tokenGroupName("names").redactionPattern("mask").build())) + .build()); + + Assert.assertEquals("My name is J**n D*e.", response.getProcessedText()); + Assert.assertEquals(Integer.valueOf(5), response.getMetrics().getWordCount()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "POST", "/v2/detect/reidentify/string"); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"text\":\"My name is [NAME_1].\"")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(body, body.contains("\"tokenGroupName\":\"names\"")); + Assert.assertTrue(body, body.contains("\"redactionPattern\":\"mask\"")); + } finally { + server.shutdown(); + } + } + + @Test + public void getRunRoundTripQueriesByIdScopedToVault() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"status\":\"SUCCESS\",\"outputType\":\"BASE64\"," + + "\"output\":[{\"processedFile\":\"UERG\",\"processedFileType\":\"REDACTED_FILE\",\"processedFileExtension\":\"pdf\"}]," + + "\"metrics\":{\"pages\":3}}")); + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"status\":\"FAILED\",\"message\":\"unsupported file\"}")); + + DetectController controller = controllerFor(server); + GetRunResponse done = controller.getRun(GetRunRequest.builder().runId(" run-42 ").build()); + Assert.assertEquals("run-42", done.getRunId()); + Assert.assertEquals(DetectRunStatus.SUCCESS, done.getStatus()); + Assert.assertEquals(DataSourceType.BASE64, done.getOutputType()); + Assert.assertEquals("UERG", done.getOutput().get(0).getProcessedFile()); + Assert.assertEquals("REDACTED_FILE", done.getOutput().get(0).getProcessedFileType()); + Assert.assertEquals(FileDataFormat.PDF, done.getOutput().get(0).getProcessedFileExtension()); + Assert.assertEquals(Integer.valueOf(3), done.getMetrics().getPages()); + Assert.assertNull(done.getMessage()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "GET", "/v2/detect/runs/run-42?vaultId=vault-1"); + Assert.assertEquals(0L, recorded.getBodySize()); + + GetRunResponse failed = controller.getRun(GetRunRequest.builder().runId("run-43").build()); + Assert.assertEquals(DetectRunStatus.FAILED, failed.getStatus()); + Assert.assertEquals("unsupported file", failed.getMessage()); + Assert.assertTrue(failed.getOutput().isEmpty()); + Assert.assertNull(failed.getOutputType()); + Assert.assertEquals("/v2/detect/runs/run-43?vaultId=vault-1", server.takeRequest().getPath()); + } finally { + server.shutdown(); + } + } + + @Test + public void checkGuardrailsRoundTrip() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"text\":\"tell me about politics\",\"validation\":\"FAILED\",\"toxic\":false,\"deniedTopic\":true}")); + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"text\":\"hello\",\"validation\":\"PASSED\"}")); + + DetectController controller = controllerFor(server); + CheckGuardrailsResponse blocked = controller.checkGuardrails(CheckGuardrailsRequest.builder() + .text("tell me about politics").checkToxicity(true).denyTopics(Arrays.asList("politics", "religion")).build()); + Assert.assertEquals("tell me about politics", blocked.getText()); + Assert.assertEquals(GuardrailsValidation.FAILED, blocked.getValidation()); + Assert.assertEquals(Boolean.FALSE, blocked.getToxic()); + Assert.assertEquals(Boolean.TRUE, blocked.getDeniedTopic()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "POST", "/v2/detect/guardrails"); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"text\":\"tell me about politics\"")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(body, body.contains("\"checkToxicity\":true")); + Assert.assertTrue(body, body.contains("\"denyTopics\":[\"politics\",\"religion\"]")); + + CheckGuardrailsResponse passed = controller.checkGuardrails(CheckGuardrailsRequest.builder().text("hello").build()); + Assert.assertEquals(GuardrailsValidation.PASSED, passed.getValidation()); + Assert.assertNull(passed.getToxic()); + Assert.assertNull(passed.getDeniedTopic()); + String minimal = server.takeRequest().getBody().readUtf8(); + Assert.assertFalse(minimal, minimal.contains("checkToxicity")); + Assert.assertFalse(minimal, minimal.contains("denyTopics")); + } finally { + server.shutdown(); + } + } + + @Test + public void apiErrorsOnInheritedMethodsMapToSkyflowException() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(404).setHeader("x-request-id", "req-404") + .setBody("{\"error\":{\"grpc_code\":5,\"http_code\":404,\"message\":\"run not found\",\"http_status\":\"Not Found\",\"details\":[]}}")); + try { + controllerFor(server).getRun(GetRunRequest.builder().runId("missing").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(404, e.getHttpCode()); + Assert.assertEquals("run not found", e.getMessage()); + Assert.assertEquals("req-404", e.getRequestId()); + Assert.assertEquals(Integer.valueOf(5), e.getGrpcCode()); + } + } finally { + server.shutdown(); + } + } + + // ─── deidentifyFile (flowvault only) ────────────────────────────────────── + + @Test + public void deidentifyFileValidatesBeforeResolvingCredentials() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), (Credentials) null); + try { + controller.deidentifyFile(DeidentifyFileRequest.builder().value("Zm9v").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.InvalidDataSourceInDeidentifyFile.getMessage(), e.getMessage()); + } + } + + @Test + public void deidentifyFileSubmitOnlyReturnsRunIdWithoutPolling() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"runId\":\"run-42\"}")); + + DeidentifyFileResponse response = controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.SKYFLOW_ID).value("rec-1").dataFormat(FileDataFormat.PDF) + .configurationId("cfg-1").build()); + + Assert.assertEquals("run-42", response.getRunId()); + Assert.assertNull(response.getStatus()); + Assert.assertTrue(response.getOutput().isEmpty()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "POST", "/v2/detect/deidentify/file"); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"dataSource\":\"SKYFLOW_ID\"")); + Assert.assertTrue(body, body.contains("\"value\":\"rec-1\"")); + Assert.assertTrue(body, body.contains("\"dataFormat\":\"pdf\"")); + Assert.assertTrue(body, body.contains("\"configurationId\":\"cfg-1\"")); + Assert.assertEquals("only the submit call was made", 1, server.getRequestCount()); + } finally { + server.shutdown(); + } + } + + @Test + public void deidentifyFilePollsToSuccessAndWritesOutputsForLocalFile() throws Exception { + File input = folder.newFile("invoice.txt"); + Files.write(input.toPath(), "Pay John Doe".getBytes("UTF-8")); + File outDir = folder.newFolder("out"); + String redacted = Base64.getEncoder().encodeToString("Pay [NAME_1]".getBytes("UTF-8")); + + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"runId\":\"run-7\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"QUEUED\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"SUCCESS\",\"outputType\":\"BASE64\"," + + "\"output\":[{\"processedFile\":\"" + redacted + "\",\"processedFileType\":\"REDACTED_FILE\",\"processedFileExtension\":\"txt\"}," + + "{\"processedFile\":\"W10=\",\"processedFileType\":\"ENTITIES\",\"processedFileExtension\":\"json\"}]," + + "\"metrics\":{\"wordCount\":3}}")); + + DeidentifyFileResponse response = controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .file(input).configurationId("cfg-1") + .pollOptions(PollOptions.builder().waitTime(1).build()) // one real 1 s sleep at most + .outputDirectory(outDir.getPath()) + .build()); + + Assert.assertEquals("run-7", response.getRunId()); + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(DataSourceType.BASE64, response.getOutputType()); + Assert.assertEquals(2, response.getOutput().size()); + Assert.assertEquals(Integer.valueOf(3), response.getMetrics().getWordCount()); + Assert.assertEquals("Pay [NAME_1]", new String(Files.readAllBytes(new File(outDir, "processed-invoice.txt").toPath()), "UTF-8")); + Assert.assertEquals("[]", new String(Files.readAllBytes(new File(outDir, "processed-entities-invoice.json").toPath()), "UTF-8")); + + RecordedRequest submit = server.takeRequest(); + assertCommonHeaders(submit, "POST", "/v2/detect/deidentify/file"); + String body = submit.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"dataSource\":\"BASE64\"")); + Assert.assertTrue(body, body.contains("\"value\":\"" + Base64.getEncoder().encodeToString("Pay John Doe".getBytes("UTF-8")) + "\"")); + Assert.assertTrue(body, body.contains("\"dataFormat\":\"txt\"")); + Assert.assertEquals("/v2/detect/runs/run-7?vaultId=vault-1", server.takeRequest().getPath()); + Assert.assertEquals("/v2/detect/runs/run-7?vaultId=vault-1", server.takeRequest().getPath()); + } finally { + server.shutdown(); + } + } + + @Test + public void deidentifyFileReturnsRunIdWithStatusWhenBudgetRunsOut() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"runId\":\"run-8\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"IN_PROGRESS\"}")); + + DeidentifyFileResponse response = controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v") + .pollOptions(PollOptions.builder().maxAttempts(1).build()).build()); + + Assert.assertEquals("run-8", response.getRunId()); + Assert.assertEquals(DetectRunStatus.IN_PROGRESS, response.getStatus()); + Assert.assertTrue(response.getOutput().isEmpty()); + Assert.assertEquals(2, server.getRequestCount()); + } finally { + server.shutdown(); + } + } + + @Test + public void deidentifyFileSurfacesFailedRunMessage() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"runId\":\"run-9\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"FAILED\",\"message\":\"unsupported file\"}")); + + DeidentifyFileResponse response = controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v").pollOptions(PollOptions.builder().build()).build()); + + Assert.assertEquals(DetectRunStatus.FAILED, response.getStatus()); + Assert.assertEquals("unsupported file", response.getMessage()); + Assert.assertEquals(2, server.getRequestCount()); + } finally { + server.shutdown(); + } + } + + @Test + public void deidentifyFileSubmitErrorMapsToSkyflowException() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); + try { + server.enqueue(new MockResponse().setResponseCode(400).setHeader("x-request-id", "req-1") + .setBody("{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"configuration not found\",\"http_status\":\"Bad Request\",\"details\":[]}}")); + try { + controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v").configurationId("missing").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(400, e.getHttpCode()); + Assert.assertEquals("configuration not found", e.getMessage()); + Assert.assertEquals("req-1", e.getRequestId()); + } + } finally { + server.shutdown(); + } + } +} diff --git a/skyvault/README.md b/skyvault/README.md index e996553a..b5302dd5 100644 --- a/skyvault/README.md +++ b/skyvault/README.md @@ -44,12 +44,12 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba - [Upload File](#upload-file) - [Detect](#detect) - - [Deidentify Text](#deidentify-text) - - [Reidentify Text](#reidentify-text) - - [Deidentify File](#deidentify-file) - - [Get Run](#get-run) - - [Detect response types](#detect-response-types) - - [Detect enums](#detect-enums) + - [Deidentify string](#deidentify-string) + - [Deidentify file](#deidentify-file) + - [Reidentify string](#reidentify-string) + - [Reidentify file](#reidentify-file) + - [Get run](#get-run) + - [Check guardrails](#check-guardrails) - [Connections](#connections) - [ConnectionController](#connectioncontroller) - [Invoke a connection](#invoke-a-connection) @@ -1664,754 +1664,277 @@ Sample response: ``` # Detect -Skyflow Detect enables you to deidentify and reidentify sensitive data in text and files, supporting advanced privacy-preserving workflows. -`DetectController` is the class returned by `skyflowClient.detect()` and `skyflowClient.detect(vaultId)`. +Skyflow Detect finds and de-identifies sensitive data in free text, then re-identifies it on demand. The skyvault SDK exposes the Detect V2 API through `DetectController`, returned by `skyflowClient.detect()` and `skyflowClient.detect(vaultId)`. Every request is scoped to that vault, and the controller honours the same credentials, timeouts and retries as `vault()`. -```java -// Uses the default (first configured) vault -DetectController detect = skyflowClient.detect(); - -// Uses a specific vault by ID -DetectController detect = skyflowClient.detect(""); -``` +Detect configurations are created in Studio or through the management API. The SDK does not create, update or delete them. -**Methods:** +| Method | Request | Response | Description | +|--------|---------|----------|-------------| +| `deidentifyString(DeidentifyStringRequest)` | `com.skyflow.detect.DeidentifyStringRequest` | `com.skyflow.detect.DeidentifyStringResponse` | Detect and replace sensitive data in a string | +| `deidentifyFile(DeidentifyFileRequest)` | `com.skyflow.detect.DeidentifyFileRequest` | `com.skyflow.detect.DeidentifyFileResponse` | Submit a file for de-identification, optionally polling the run to completion | +| `reidentifyString(ReidentifyStringRequest)` | `com.skyflow.detect.ReidentifyStringRequest` | `com.skyflow.detect.ReidentifyStringResponse` | Replace tokens in a string with their original or redacted values | +| `reidentifyFile(ReidentifyFileRequest)` | `com.skyflow.detect.ReidentifyFileRequest` | `com.skyflow.detect.ReidentifyFileResponse` | Replace tokens in a file with their original or redacted values | +| `getRun(GetRunRequest)` | `com.skyflow.detect.GetRunRequest` | `com.skyflow.detect.GetRunResponse` | Retrieve the status and outputs of a Detect file run | +| `checkGuardrails(CheckGuardrailsRequest)` | `com.skyflow.detect.CheckGuardrailsRequest` | `com.skyflow.detect.CheckGuardrailsResponse` | Screen text for toxicity and denied topics | -| Method | Parameters | Returns | Description | -|--------|-----------|---------|-------------| -| `deidentifyText(DeidentifyTextRequest)` | [`DeidentifyTextRequest`](../docs/api_reference.md#deidentifytextrequest) | [`DeidentifyTextResponse`](../docs/api_reference.md#deidentifytextresponse) | Deidentify sensitive entities in text | -| `reidentifyText(ReidentifyTextRequest)` | [`ReidentifyTextRequest`](../docs/api_reference.md#reidentifytextrequest) | [`ReidentifyTextResponse`](../docs/api_reference.md#reidentifytextresponse) | Restore original values from a deidentified text | -| `deidentifyFile(DeidentifyFileRequest)` | [`DeidentifyFileRequest`](../docs/api_reference.md#deidentifyfilerequest) | [`DeidentifyFileResponse`](../docs/api_reference.md#deidentifyfileresponse) | Deidentify sensitive data in a file | -| `getDetectRun(GetDetectRunRequest)` | [`GetDetectRunRequest`](../docs/api_reference.md#getdetectrunrequest) | [`DeidentifyFileResponse`](../docs/api_reference.md#deidentifyfileresponse) | Poll for the result of an async file deidentification | +> Detect V2 is in beta. -## Deidentify Text -To deidentify text, use the `deidentifyText` method. [`DeidentifyTextRequest`](../docs/api_reference.md#deidentifytextrequest) accepts the text to deidentify along with optional entity types, regex lists, token format, and transformations. Returns a [`DeidentifyTextResponse`](../docs/api_reference.md#deidentifytextresponse). +## Deidentify string -### Construct an deidentify text request +`DeidentifyStringRequest` takes the text plus, optionally, `configurationId` (a stored Detect configuration) and/or `configuration` (an inline `DetectConfiguration`). Both are optional on the API and are sent exactly as supplied. The SDK fills the vault id from the controller. ```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: Initialize 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(); +import com.skyflow.detect.*; + +// Stored configuration +DeidentifyStringResponse response = skyflowClient.detect().deidentifyString( + DeidentifyStringRequest.builder() + .text("My name is John Doe, and my email is johndoe@acme.com.") + .configurationId("") + .build()); + +System.out.println(response.getProcessedText()); +// My name is [NAME_1], and my email is [EMAIL_ADDRESS_1]. + +// Inline configuration +DetectConfiguration configuration = DetectConfiguration.builder() + .detect(Detect.builder() + .entities(Arrays.asList( + Entity.builder() + .entityType(EntityType.NAME) + .deidentificationType(DeidentificationType.VAULT_TOKEN) + .destination(".") // skyvault: table.column that stores the value + .build(), + Entity.builder() + .entityType(EntityType.ALL) + .deidentificationType(DeidentificationType.ENTITY_UNIQUE_COUNTER) + .build())) + .skip(Collections.singletonList("Skyflow")) + .returnEntities(ReturnEntitiesType.EXCLUDE_SENSITIVE_DATA) + .build()) + .build(); - // Step 4: Use the Skyflow client to perform the deidentifyText operation - // Replace with your actual vault ID - DeidentifyTextResponse deidentifyTextResponse = skyflowClient.detect("").deidentifyText(deidentifyTextRequest); +response = skyflowClient.detect().deidentifyString( + DeidentifyStringRequest.builder() + .text("My name is John Doe, and my email is johndoe@acme.com.") + .configuration(configuration) + .build()); - // Step 5: Print the response - System.out.println("Deidentify text Response: " + deidentifyTextResponse); - } +for (DetectedEntity entity : response.getEntities()) { + System.out.println(entity.getEntityType() + " " + entity.getToken() + + " [" + entity.getLocation().getStartIndex() + "," + entity.getLocation().getEndIndex() + "]"); } - +System.out.println(response.getMetrics().getWordCount()); ``` -## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/DeidentifyTextExample.java) of deidentify text: -```java -import java.util.ArrayList; -import java.util.List; - -import com.skyflow.enums.DetectEntities; -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.detect.DateTransformation; -import com.skyflow.vault.detect.DeidentifyTextRequest; -import com.skyflow.vault.detect.DeidentifyTextResponse; -import com.skyflow.vault.detect.TokenFormat; -import com.skyflow.vault.detect.Transformations; - -/** - * Skyflow Deidentify Text Example - *

- * This example demonstrates how to use the Skyflow SDK to deidentify text data - * across multiple vaults. It includes: - * 1. Setting up credentials and vault configurations. - * 2. Creating a Skyflow client with multiple vaults. - * 3. Performing deidentify of text with various options. - * 4. Handling responses and errors. - */ - -public class DeidentifyTextExample { - public static void main(String[] args) throws SkyflowException { - - // Step 1: Initialize 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 +`DeidentifyStringResponse` carries `getProcessedText()`, `getEntities()` (a `List` with token, entity type, location and confidence scores; never `null`) and `getMetrics()`. - 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 actual 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. [`ReidentifyTextRequest`](../docs/api_reference.md#reidentifytextrequest) accepts the redacted/deidentified text and optional entity lists controlling which entities to reveal, mask, or keep redacted. Returns a [`ReidentifyTextResponse`](../docs/api_reference.md#reidentifytextresponse). - -### 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: Initialize 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 +## Deidentify file +File de-identification is asynchronous on the API: the submit call returns a run id and the result is retrieved from the run. `deidentifyFile` exposes both modes. - // 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(); +- **Submit only** (default): one call, returns `getRunId()`. `getStatus()` is `null` and nothing is written to disk. Retrieve the result later with [`getRun`](#get-run). +- **Submit and poll**: set `pollOptions`. The SDK polls the run with exponential backoff (1, 2, 4, 8, 16, then 32 seconds between lookups) until it is `SUCCESS`, `FAILED` or `UNKNOWN`, or until `waitTime` (default 60 s, max 300) or `maxAttempts` (default 23, max 23) is used up. If the budget runs out the response carries the run id with `IN_PROGRESS` or `QUEUED` so you can resume with `getRun`. - // Step 4: Invoke reidentify text on the vault - ReidentifyTextResponse reidentifyTextResponse = skyflowClient.detect("").reidentifyText(reidentifyTextRequest); - System.out.println("Reidentify text Response: " + reidentifyTextResponse); - } -} -``` - -## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/ReidentifyTextExample.java) of Reidentify text +The file is supplied in one of three ways: `dataSource` plus `value` (`BASE64` content, a `SKYFLOW_ID`, or a `PRESIGNED_URL`), or `file(File)` / `filePath(String)`, which read and encode a local file and infer `dataFormat` from its extension. Supply exactly one of `value`, `file` or `filePath`. Either `configurationId` or an inline `configuration` is passed through as given. ```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: Initialize 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 actual 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(); - } - } +// Submit only +DeidentifyFileResponse submitted = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("/data/intake/patient-notes.pdf") // BASE64 + pdf inferred + .configurationId("") + .build()); +String runId = submitted.getRunId(); + +// Submit and poll +DeidentifyFileResponse response = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("/data/intake/patient-notes.pdf") + .configurationId("") + .pollOptions(PollOptions.builder().waitTime(120).build()) + .outputDirectory("/data/processed") // optional + .build()); + +switch (response.getStatus()) { + case SUCCESS: + // For file-based requests the outputs are already on disk: + // /data/processed/processed-patient-notes.pdf the redacted file + // /data/processed/processed-entities-patient-notes.json the detected entities + // response.getOutput() and getMetrics() carry the same data. + break; + case FAILED: + System.err.println(response.getMessage()); + break; + default: // IN_PROGRESS or QUEUED: budget ran out, resume with getRun(runId) + break; } ``` -Sample Response: +Outputs are written only when polling reached `SUCCESS`, the request was built from a local file, and the run delivered them as base64. A request built from a `SKYFLOW_ID` or `PRESIGNED_URL` has no local name to derive from, and presigned-URL outputs are not fetched, so in those cases read `getOutput()` and write the files yourself. Files are named `processed-.`, with the entities output as `processed-entities-.json` (and `processed-object-entities-.json` for object entities); `outputDirectory` is created if missing and defaults to the working directory. Polling blocks the calling thread. -```json -{ - "processedText":"My SSN is 123-45-6789 and my card is XXXXX1111." -} -``` - -## Deidentify file -To deidentify files, use the `deidentifyFile` method. [`DeidentifyFileRequest`](../docs/api_reference.md#deidentifyfilerequest) accepts a [`FileInput`](../docs/api_reference.md#fileinput) and optional parameters controlling entity detection, masking, output format, and async wait time. Supports images, PDFs, audio, documents, spreadsheets, and presentations. Returns a [`DeidentifyFileResponse`](../docs/api_reference.md#deidentifyfileresponse). - -### AudioBleep - -[`AudioBleep`](../docs/api_reference.md#audiobleep) controls how detected sensitive audio segments are replaced with a bleep tone. Used in `DeidentifyFileRequest.builder().bleep(audioBleep)` for audio files. - -```java -import com.skyflow.vault.detect.AudioBleep; +### Polling from a worker thread -AudioBleep audioBleep = AudioBleep.builder() - .frequency(1000D) // bleep tone frequency in Hz - .gain(0.5D) // bleep tone gain (volume level) - .startPadding(0.2D) // silence padding before the bleep (seconds) - .stopPadding(0.2D) // silence padding after the bleep (seconds) - .build(); -``` +With `pollOptions` set, `deidentifyFile` polls on the thread that called it: each lookup is a synchronous `getRun` followed by a sleep, until the run is terminal or the budget runs out. No other thread, lock or connection is held while it waits, so other SDK calls are unaffected, but the calling thread is. If that thread is your main thread, a request thread or an event loop, run the call elsewhere. -### Construct an deidentify file request +**Run the blocking call on a thread you own.** Simplest when you process a few files at a time. The SDK still enforces the budget and writes outputs to disk; your thread is parked for the whole poll. ```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: Initialize 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()); +ExecutorService pool = Executors.newFixedThreadPool(4); // or Executors.newVirtualThreadPerTaskExecutor() on JDK 21+ + +pool.execute(() -> { + try { + DeidentifyFileResponse response = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("/data/intake/patient-notes.pdf") + .configurationId("") + .pollOptions(PollOptions.builder().waitTime(120).build()) + .outputDirectory("/data/processed") + .build()); + handle(response); // SUCCESS, FAILED, UNKNOWN, or IN_PROGRESS/QUEUED if the budget ran out + } catch (SkyflowException e) { + handleError(e); // catch inside the task; an uncaught exception only ends this thread } -} +}); ``` -## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/DeidentifyFileExample.java) of Deidentify file +Use `pool.submit(...)` instead of `execute` if you want a `Future` to cancel with: interrupting the thread wakes the sleep and the SDK returns the last run it saw. Bound the pool, since every in-flight run parks one thread. + +**Submit only, then poll `getRun` on a scheduler.** Best for services and anything concurrent. No thread is held between lookups, so one scheduler thread serves any number of runs. You control the backoff and budget, and you write the outputs yourself since the SDK only writes them when it polls. ```java -import java.io.File; +ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); -import com.skyflow.enums.MaskingMethod; -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.detect.DeidentifyFileRequest; -import com.skyflow.vault.detect.DeidentifyFileResponse; +String runId = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("/data/intake/patient-notes.pdf") + .configurationId("") + .build()) // no pollOptions: returns the run id immediately + .getRunId(); -/** - * 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 { +scheduler.schedule(new Runnable() { + long delaySeconds = 1; - public static void main(String[] args) throws SkyflowException { - // Step 1: Initialize the Skyflow client by configuring the credentials & vault config. + @Override + public void run() { try { - // Step 2: Create a deidentify file request with all options - - - // Create file object - File file = new File("sensitive-folder/personal-info.txt"); // Replace with the path to the file you want to deidentify - - // Create file input using the file object - FileInput fileInput = FileInput.builder() - .file(file) - // .filePath("") // Alternatively, you can use .filePath() - .build(); - - // Output configuration - String outputDirectory = "deidentified-file/"; // Replace with the desired output directory to save the deidentified file - - // Entities to detect - // List detectEntities = new ArrayList<>(); - // detectEntities.add(DetectEntities.IP_ADDRESS); // Replace with the entities you want to detect - - // Image-specific options - // Boolean outputProcessedImage = true; // Include processed image in output - // Boolean outputOcrText = true; // Include OCR text in output - MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; // Masking method for images - - Integer waitTime = 20; // Max wait time for response (max 64 seconds) - - DeidentifyFileRequest deidentifyFileRequest = DeidentifyFileRequest.builder() - .file(fileInput) - .waitTime(waitTime) - .outputDirectory(outputDirectory) - .maskingMethod(maskingMethod) - .build(); - - // Step 3: Invoking deidentifyFile - // Replace `9f27764a10f7946fe56b3258e117` with the actual vault id - DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect("9f27764a10f7946fe56b3258e117").deidentifyFile(deidentifyFileRequest); - System.out.println("Deidentify file response: " + deidentifyFileResponse.toString()); + GetRunResponse run = skyflowClient.detect().getRun(GetRunRequest.builder().runId(runId).build()); + switch (run.getStatus()) { + case SUCCESS: case FAILED: case UNKNOWN: + handle(run); + return; + default: // QUEUED, IN_PROGRESS + scheduler.schedule(this, delaySeconds, TimeUnit.SECONDS); + delaySeconds = Math.min(delaySeconds * 2, 32); + } } catch (SkyflowException e) { - System.err.println("Error occurred during deidentify file: "); - e.printStackTrace(); + handleError(e); } } -} - -``` - -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" -} - +}, 0, TimeUnit.SECONDS); ``` -**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` +Either way the main thread only pays for the submit round trip. Avoid `new Thread(...)` per file or `CompletableFuture.runAsync` on the common pool for anything that runs at scale: the first has no bound on threads, and the second blocks a shared pool sized for CPU work. -**Note:** -- Transformations cannot be applied to Documents, Images, or PDFs file formats. +## Reidentify string -- 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. [`GetDetectRunRequest`](../docs/api_reference.md#getdetectrunrequest) accepts the `runId` returned from a prior `deidentifyFile` call. Returns a [`DeidentifyFileResponse`](../docs/api_reference.md#deidentifyfileresponse). - -### Construct an get run request +`ReidentifyStringRequest` takes the tokenized text and an optional list of `RedactionLevel` rules. For skyvault vaults each rule names an `entityName` and the `redactionType` to apply to it: `PLAIN_TEXT` reveals the original value, `MASKED` masks it, `REDACTED` keeps the token, `DEFAULT` applies the vault's default. Without rules every token is replaced by its original value. ```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: Initialize 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(); - } - } -} +ReidentifyStringResponse response = skyflowClient.detect().reidentifyString( + ReidentifyStringRequest.builder() + .text("My name is [NAME_1] and my email is [EMAIL_ADDRESS_1].") + .redactionLevel(Arrays.asList( + RedactionLevel.builder() + .entityName(EntityType.NAME) + .redactionType(RedactionType.PLAIN_TEXT) + .build(), + RedactionLevel.builder() + .entityName(EntityType.EMAIL_ADDRESS) + .redactionType(RedactionType.MASKED) + .build())) + .build()); +System.out.println(response.getProcessedText()); +// My name is John Doe and my email is j*******@acme.com. ``` -## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/GetDetectRunExample.java) of get run -```java -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Env; -import com.skyflow.enums.LogLevel; -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.detect.DeidentifyFileResponse; -import com.skyflow.vault.detect.GetDetectRunRequest; +A `RedactionLevel` is expected to name one source (`entityName`) and one replacement (`redactionType`). Every field is optional on the API, so the SDK passes the list through as given and the server enforces the combination rules. The `tokenGroupName` and `redactionPattern` fields apply to flowvault vaults only. -/** - * 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: Initialize the Skyflow client by configuring the credentials & vault config. - try { +## Reidentify file - // 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(); +`reidentifyFile` is synchronous: the re-identified file comes back in the response, not through a run id. `ReidentifyFileRequest` takes a `dataSource` (`BASE64`, `SKYFLOW_ID` or `PRESIGNED_URL`), the matching `value`, an optional `dataFormat` and the same optional `RedactionLevel` rules as `reidentifyString`. Re-identification supports text-based formats such as TXT, CSV, JSON, JSONL, XML, DOCX, XLSX and PPTX. - // Step 3: Call getDetectRun to poll for file processing results - // Replace `9f27764a10f7946fe56b3258e117` with the actual 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" +```java +byte[] content = Files.readAllBytes(Paths.get("tokenized.txt")); + +ReidentifyFileResponse response = skyflowClient.detect().reidentifyFile( + ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64) + .value(Base64.getEncoder().encodeToString(content)) + .dataFormat(FileDataFormat.TXT) + .redactionLevel(Collections.singletonList( + RedactionLevel.builder() + .entityName(EntityType.NAME) + .redactionType(RedactionType.PLAIN_TEXT) + .build())) + .build()); + +if (response.getStatus() == DetectRunStatus.SUCCESS) { + for (FileOutput output : response.getOutput()) { + // output.getProcessedFile() is base64 or a presigned URL, per response.getOutputType() + byte[] processed = Base64.getDecoder().decode(output.getProcessedFile()); } - ], - "runId": "e0038196-4a20-422b-bad7-e0477117f9bb", - "status": "success" } - ``` -## Detect response types +`ReidentifyFileResponse` carries `getStatus()`, `getOutputType()`, `getOutput()` (never `null`) and `getMetrics()`. -The Detect API returns structured objects for detected entities. See the API Reference for full attribute lists: [`EntityInfo`](../docs/api_reference.md#entityinfo), [`TextIndex`](../docs/api_reference.md#textindex), [`FileEntityInfo`](../docs/api_reference.md#fileentityinfo), [`FileInfo`](../docs/api_reference.md#fileinfo). +## Get run -### EntityInfo and TextIndex - -[`EntityInfo`](../docs/api_reference.md#entityinfo) appears in `DeidentifyTextResponse.getEntities()`. Each entry includes the detected entity type, original value, replacement token, character positions ([`TextIndex`](../docs/api_reference.md#textindex)), and confidence scores. +File de-identification is asynchronous: the submit call returns a run id, and `getRun` retrieves the run's status and, once it has succeeded, its outputs. `GetRunResponse.getOutput()` is empty and `getOutputType()` and `getMetrics()` are `null` until the run completes. ```java -DeidentifyTextResponse response = skyflowClient.detect("").deidentifyText(request); - -for (EntityInfo entity : response.getEntities()) { - System.out.println("Entity : " + entity.getEntity()); - System.out.println("Value : " + entity.getValue()); - System.out.println("Token : " + entity.getToken()); - System.out.println("Start : " + entity.getTextIndex().getStart()); - System.out.println("End : " + entity.getTextIndex().getEnd()); - System.out.println("Score : " + entity.getScores().get(entity.getEntity())); +GetRunResponse run = skyflowClient.detect().getRun( + GetRunRequest.builder().runId("").build()); + +switch (run.getStatus()) { + case SUCCESS: + for (FileOutput output : run.getOutput()) { + // output.getProcessedFile() is base64 or a presigned URL, per run.getOutputType() + // output.getProcessedFileType() is e.g. REDACTED_FILE or ENTITIES + // output.getProcessedFileExtension() is a FileDataFormat such as PDF + } + break; + case FAILED: + System.err.println(run.getMessage()); + break; + default: // QUEUED, IN_PROGRESS, UNKNOWN + // poll again later } ``` -### FileEntityInfo and FileInfo - -[`FileEntityInfo`](../docs/api_reference.md#fileentityinfo) appears in `DeidentifyFileResponse.getEntities()`. [`FileInfo`](../docs/api_reference.md#fileinfo) is returned by `DeidentifyFileResponse.getFile()` and contains file metadata. - -## Detect enums - -See the API Reference for full value descriptions: [`TokenType`](../docs/api_reference.md#tokentype), [`DeidentifyFileStatus`](../docs/api_reference.md#deidentifyfilestatus), [`DetectOutputTranscriptions`](../docs/api_reference.md#detectoutputtranscriptions), [`MaskingMethod`](../docs/api_reference.md#maskingmethod), [`DetectEntities`](../docs/api_reference.md#detectentities). +## Check guardrails -### TokenType - -[`TokenType`](../docs/api_reference.md#tokentype) controls how detected entities are tokenized. Used in `TokenFormat.builder()`. - -```java -import com.skyflow.enums.TokenType; - -TokenFormat tokenFormat = TokenFormat.builder() - .vaultToken(vaultTokenList) // uses VAULT_TOKEN - .entityOnly(entityOnlyList) // uses ENTITY_ONLY - .entityUniqueCounter(entityUniqueCounterList) // uses ENTITY_UNIQUE_COUNTER - .build(); -``` - -### DeidentifyFileStatus - -[`DeidentifyFileStatus`](../docs/api_reference.md#deidentifyfilestatus) is returned in `DeidentifyFileResponse.getStatus()` to indicate async processing state. +`checkGuardrails` screens text for toxicity and for a list of denied topics, which makes it a natural pre-LLM check. Each check runs only when requested: `getToxic()` is `null` unless `checkToxicity(true)` was set, and `getDeniedTopic()` is `null` unless `denyTopics` was supplied. `getValidation()` is `FAILED` if any requested check triggered. ```java -import com.skyflow.enums.DeidentifyFileStatus; - -DeidentifyFileResponse response = skyflowClient.detect("").getDetectRun(request); -if (DeidentifyFileStatus.SUCCESS.value().equals(response.getStatus())) { - // safe to read response.getFile() -} else if (DeidentifyFileStatus.IN_PROGRESS.value().equals(response.getStatus())) { - // poll again using the runId +CheckGuardrailsResponse response = skyflowClient.detect().checkGuardrails( + CheckGuardrailsRequest.builder() + .text(userPrompt) + .checkToxicity(true) + .denyTopics(Arrays.asList("politics", "medical advice")) + .build()); + +if (response.getValidation() == GuardrailsValidation.FAILED) { + throw new IllegalArgumentException("blocked: toxic=" + response.getToxic() + " deniedTopic=" + response.getDeniedTopic()); } ``` -### DetectOutputTranscriptions +All Detect methods throw `SkyflowException` as described in [Error Handling](#error-handling). Client-side validation fails before any network call. -[`DetectOutputTranscriptions`](../docs/api_reference.md#detectoutputtranscriptions) controls the transcription format for audio file deidentification. - -```java -import com.skyflow.enums.DetectOutputTranscriptions; - -DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .outputTranscription(DetectOutputTranscriptions.TRANSCRIPTION) - .build(); -``` +See the samples [DeidentifyStringSample.java](samples/src/main/java/com/example/detect/DeidentifyStringSample.java), [DeidentifyFileSample.java](samples/src/main/java/com/example/detect/DeidentifyFileSample.java), [ReidentifyStringSample.java](samples/src/main/java/com/example/detect/ReidentifyStringSample.java), [ReidentifyFileSample.java](samples/src/main/java/com/example/detect/ReidentifyFileSample.java), [GetRunSample.java](samples/src/main/java/com/example/detect/GetRunSample.java) and [CheckGuardrailsSample.java](samples/src/main/java/com/example/detect/CheckGuardrailsSample.java). # Connections diff --git a/skyvault/api-report/skyflow-java.baseline.jar b/skyvault/api-report/skyflow-java.baseline.jar index 6ba58495..dc2ace2b 100644 Binary files a/skyvault/api-report/skyflow-java.baseline.jar and b/skyvault/api-report/skyflow-java.baseline.jar differ diff --git a/skyvault/pom.xml b/skyvault/pom.xml index ce14cc82..083d5676 100644 --- a/skyvault/pom.xml +++ b/skyvault/pom.xml @@ -23,6 +23,12 @@ + + com.squareup.okhttp3 + mockwebserver + ${okhttp-version} + test + com.skyflow common @@ -57,26 +63,19 @@ - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.6.0 - + shade-for-japicmp package @@ -170,7 +169,7 @@ jfrog - central + skyflow-jfrog prekarilabs.jfrog.io-releases https://prekarilabs.jfrog.io/artifactory/skyflow-java diff --git a/skyvault/samples/pom.xml b/skyvault/samples/pom.xml index 3797c62c..ec3f090c 100644 --- a/skyvault/samples/pom.xml +++ b/skyvault/samples/pom.xml @@ -18,7 +18,7 @@ com.skyflow skyflow-java - 2.0.3 + 2.1.1 diff --git a/skyvault/samples/src/main/java/com/example/detect/CheckGuardrailsSample.java b/skyvault/samples/src/main/java/com/example/detect/CheckGuardrailsSample.java new file mode 100644 index 00000000..25947b1a --- /dev/null +++ b/skyvault/samples/src/main/java/com/example/detect/CheckGuardrailsSample.java @@ -0,0 +1,51 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.CheckGuardrailsResponse; +import com.skyflow.detect.GuardrailsValidation; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.util.Arrays; + +/** + * Screens text for toxicity and denied topics before it reaches an LLM. + */ +public class CheckGuardrailsSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + try { + CheckGuardrailsResponse response = skyflowClient.detect().checkGuardrails( + CheckGuardrailsRequest.builder() + .text("Which candidate should I vote for in the upcoming election?") + .checkToxicity(true) // server default is true when omitted + .denyTopics(Arrays.asList("politics", "medical advice")) + .build()); + System.out.println("Validation: " + response.getValidation() + + " toxic=" + response.getToxic() + " deniedTopic=" + response.getDeniedTopic()); + if (response.getValidation() == GuardrailsValidation.FAILED) { + System.out.println("Blocked by guardrails"); + } + } catch (SkyflowException e) { + System.err.println("Error during checkGuardrails:"); + e.printStackTrace(); + } + } +} diff --git a/skyvault/samples/src/main/java/com/example/detect/DeidentifyFileExample.java b/skyvault/samples/src/main/java/com/example/detect/DeidentifyFileExample.java deleted file mode 100644 index 214aa42d..00000000 --- a/skyvault/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.ERROR) // Set log level to ERROR - .addVaultConfig(vaultConfig) // Add the vault configuration - .build(); - - try { - - // Step 4: Create a deidentify file request with all options - - // Create file object - File file = new File("") // Alternatively, you can use .filePath() - .build(); - - // Output configuration - String outputDirectory = ""; // Replace with the desired output directory to save the deidentified file - - // Entities to detect - // List detectEntities = new ArrayList<>(); - // detectEntities.add(DetectEntities.IP_ADDRESS); // Replace with the entities you want to detect - - // Image-specific options - // Boolean outputProcessedImage = true; // Include processed image in output - // Boolean outputOcrText = true; // Include OCR text in output - MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; // Masking method for images - - // PDF-specific options - // Integer pixelDensity = 15; // Pixel density for PDF processing - // Integer maxResolution = 2000; // Max resolution for PDF - - // Audio-specific options - // Boolean outputProcessedAudio = true; // Include processed audio - // DetectOutputTranscriptions outputTanscription = DetectOutputTranscriptions.PLAINTEXT_TRANSCRIPTION; // Transcription type - - // Audio bleep configuration - // AudioBleep audioBleep = AudioBleep.builder() - // .frequency(5D) // Pitch in Hz - // .startPadding(7D) // Padding at start (seconds) - // .stopPadding(8D) // Padding at end (seconds) - // .build(); - - Integer waitTime = 20; // Max wait time for response (max 64 seconds) - - DeidentifyFileRequest deidentifyFileRequest = DeidentifyFileRequest.builder() - .file(fileInput) - .waitTime(waitTime) - // .entities(detectEntities) - .outputDirectory(outputDirectory) - .maskingMethod(maskingMethod) - // .outputProcessedImage(outputProcessedImage) - // .outputOcrText(outputOcrText) - // .pixelDensity(pixelDensity) - // .maxResolution(maxResolution) - // .outputProcessedAudio(outputProcessedAudio) - // .outputTranscription(outputTanscription) - // .bleep(audioBleep) - .build(); - - - DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect(vaultConfig.getVaultId()).deidentifyFile(deidentifyFileRequest); - System.out.println("Deidentify file response: " + deidentifyFileResponse.toString()); - } catch (SkyflowException e) { - System.err.println("Error occurred during deidentify file: "); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/skyvault/samples/src/main/java/com/example/detect/DeidentifyFileExampleAsync.java b/skyvault/samples/src/main/java/com/example/detect/DeidentifyFileExampleAsync.java deleted file mode 100644 index 651542f8..00000000 --- a/skyvault/samples/src/main/java/com/example/detect/DeidentifyFileExampleAsync.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.example.detect; - -import java.io.File; -import java.util.concurrent.CompletableFuture; - -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 Async Example - *

- * This example demonstrates how to use the Skyflow SDK to deidentify file in an asynchronous manner. - * 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 DeidentifyFileExampleAsync { - - public static void main(String[] args) throws SkyflowException { - // Step 1: Set up credentials for the first vault configuration - Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the path to the credentials file - - // Step 2: Configure the vault config - VaultConfig vaultConfig = new VaultConfig(); - vaultConfig.setVaultId(""); // Replace with the ID of the vault - vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault - vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - vaultConfig.setCredentials(credentials); // Associate the credentials with the vault - - // Step 3: Create a Skyflow client - Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.ERROR) // Set log level to ERROR - .addVaultConfig(vaultConfig) // Add the vault configuration - .build(); - - // Step 4: 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(); - - CompletableFuture future = CompletableFuture.supplyAsync(() -> { - try { - return skyflowClient.detect(vaultConfig.getVaultId()).deidentifyFile(deidentifyFileRequest); - } catch (SkyflowException e) { - throw new RuntimeException(e); - } - }).thenAccept(response -> { - System.out.println("Deidentify file response: " + response.toString()); - }).exceptionally(throwable -> { - System.err.println("Error occurred during deidentify file: "); - throwable.printStackTrace(); - return null; - }); - - future.join(); - } -} diff --git a/skyvault/samples/src/main/java/com/example/detect/DeidentifyFileSample.java b/skyvault/samples/src/main/java/com/example/detect/DeidentifyFileSample.java new file mode 100644 index 00000000..4b3c8b8d --- /dev/null +++ b/skyvault/samples/src/main/java/com/example/detect/DeidentifyFileSample.java @@ -0,0 +1,74 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyFileResponse; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.PollOptions; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +/** + * De-identifies a local file. The first call submits the run and returns its id; the second + * submits and polls until the run completes, writing the outputs to disk on success. + */ +public class DeidentifyFileSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + // 1. Submit only: returns the run id, retrieve the result later with getRun. + try { + DeidentifyFileResponse submitted = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("") // BASE64 data source, format inferred from the extension + .configurationId("") // Replace with a Detect configuration id + .build()); + System.out.println("Run id: " + submitted.getRunId()); // getStatus() is null, nothing written to disk + } catch (SkyflowException e) { + System.err.println("Error during deidentifyFile (submit only):"); + e.printStackTrace(); + } + + // 2. Submit and poll: blocks the calling thread until the run is terminal or the budget runs out. + try { + DeidentifyFileResponse response = skyflowClient.detect().deidentifyFile( + DeidentifyFileRequest.builder() + .filePath("") + .configurationId("") + .pollOptions(PollOptions.builder().waitTime(120).build()) // 1..300 s, default 60 + .outputDirectory("") // optional, defaults to the working directory + .build()); + System.out.println("Run id: " + response.getRunId() + " status: " + response.getStatus()); + if (response.getStatus() == DetectRunStatus.SUCCESS) { + // Outputs are already on disk as processed-. and processed-entities-.json + for (FileOutput output : response.getOutput()) { + System.out.println(output.getProcessedFileType() + " -> " + output.getProcessedFileExtension()); + } + System.out.println("Pages: " + response.getMetrics().getPages()); + } else if (response.getStatus() == DetectRunStatus.FAILED) { + System.err.println("Run failed: " + response.getMessage()); + } else { + System.out.println("Budget ran out, resume with getRun(" + response.getRunId() + ")"); + } + } catch (SkyflowException e) { + System.err.println("Error during deidentifyFile (submit and poll):"); + e.printStackTrace(); + } + } +} diff --git a/skyvault/samples/src/main/java/com/example/detect/DeidentifyStringSample.java b/skyvault/samples/src/main/java/com/example/detect/DeidentifyStringSample.java new file mode 100644 index 00000000..d9891753 --- /dev/null +++ b/skyvault/samples/src/main/java/com/example/detect/DeidentifyStringSample.java @@ -0,0 +1,93 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.DeidentificationType; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.DeidentifyStringResponse; +import com.skyflow.detect.Detect; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.DetectedEntity; +import com.skyflow.detect.Entity; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.ReturnEntitiesType; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.util.Arrays; +import java.util.Collections; + +/** + * De-identifies sensitive data in a string, first with a stored Detect configuration and then + * with an inline configuration. For a skyvault vault a VAULT_TOKEN entity's destination is the + * "table.column" that stores the value. + */ +public class DeidentifyStringSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + String text = "My name is John Doe, and my email is johndoe@acme.com."; + + // 1. Stored configuration, created in Studio or through the management API. + try { + DeidentifyStringResponse response = skyflowClient.detect().deidentifyString( + DeidentifyStringRequest.builder() + .text(text) + .configurationId("") // Replace with a Detect configuration id + .build()); + System.out.println("Processed text: " + response.getProcessedText()); + } catch (SkyflowException e) { + System.err.println("Error during deidentifyString (stored configuration):"); + e.printStackTrace(); + } + + // 2. Inline configuration, nothing to create beforehand. + DetectConfiguration configuration = DetectConfiguration.builder() + .detect(Detect.builder() + .entities(Arrays.asList( + Entity.builder() + .entityType(EntityType.NAME) + .deidentificationType(DeidentificationType.VAULT_TOKEN) + .destination("persons.name") // skyvault: table.column that stores the value + .build(), + Entity.builder() + .entityType(EntityType.ALL) + .deidentificationType(DeidentificationType.ENTITY_UNIQUE_COUNTER) + .build())) + .skip(Collections.singletonList("Skyflow")) + .returnEntities(ReturnEntitiesType.EXCLUDE_SENSITIVE_DATA) + .build()) + .build(); + + try { + DeidentifyStringResponse response = skyflowClient.detect().deidentifyString( + DeidentifyStringRequest.builder() + .text(text) + .configuration(configuration) + .build()); + System.out.println("Processed text: " + response.getProcessedText()); + for (DetectedEntity entity : response.getEntities()) { + System.out.println(entity.getEntityType() + " " + entity.getToken() + + " [" + entity.getLocation().getStartIndex() + "," + entity.getLocation().getEndIndex() + "]"); + } + System.out.println("Word count: " + response.getMetrics().getWordCount()); + } catch (SkyflowException e) { + System.err.println("Error during deidentifyString (inline configuration):"); + e.printStackTrace(); + } + } +} diff --git a/skyvault/samples/src/main/java/com/example/detect/DeidentifyTextExample.java b/skyvault/samples/src/main/java/com/example/detect/DeidentifyTextExample.java deleted file mode 100644 index 1611f9bb..00000000 --- a/skyvault/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.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - blitzConfig.setCredentials(credentials); // Associate the credentials with the vault - - // Step 3: Configure the second vault (Stage) - VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); // Replace with the ID of the second vault - stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault - stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault - - // Step 4: Set up credentials for the Skyflow client - Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file - - // Step 5: Create a Skyflow client and add vault configurations - Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.ERROR) // Set log level to ERROR - .addVaultConfig(blitzConfig) // Add the first vault configuration - .addVaultConfig(stageConfig) // Add the second vault configuration - .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials - .build(); - - // Step 6: Configuring the different options for deidentify - // Replace with the entity you want to detect - List detectEntitiesList = new ArrayList<>(); - detectEntitiesList.add(DetectEntities.SSN); - detectEntitiesList.add(DetectEntities.CREDIT_CARD); - - // Replace with the entity you want to detect with vault token - List vaultTokenList = new ArrayList<>(); - vaultTokenList.add(DetectEntities.SSN); - vaultTokenList.add(DetectEntities.CREDIT_CARD); - - // Replace with the entity you want to detect with entity only - // List entityOnlyList = new ArrayList<>(); - // entityOnlyList.add(DetectEntities.SSN); - - // Replace with the entity you want to detect with entity unique counter - // List entityUniqueCounterList = new ArrayList<>(); - // entityUniqueCounterList.add(DetectEntities.SSN); - - // Replace with the regex patterns you want to allow during deidentification - // List allowRegexList = new ArrayList<>(); - // allowRegexList.add(""); - - // Replace with the regex patterns you want to restrict during deidentification - // List restrictRegexList = new ArrayList<>(); - // restrictRegexList.add("YOUR_RESTRICT_REGEX_LIST"); - - // Configure Token Format - TokenFormat tokenFormat = TokenFormat.builder() - .vaultToken(vaultTokenList) - // .entityOnly(entityOnlyList) - // .entityUniqueCounter(entityUniqueCounterList) - .build(); - - // Configure Transformation for deidentified entities - // List detectEntitiesTransformationList = new ArrayList<>(); - // detectEntitiesTransformationList.add(DetectEntities.DOB); // Replace with the entity you want to transform - // detectEntitiesTransformationList.add(DetectEntities.DATE); - - // DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); - // Transformations transformations = new Transformations(dateTransformation); - - // Example 1: Deidentify text on the first vault - try { - // Create a deidentify text request for the first vault - DeidentifyTextRequest deidentifyTextRequest = DeidentifyTextRequest.builder() - .text("My SSN is 123-45-6789 and my card is 4111 1111 1111 1111.") // Replace with the text you want to deidentify - .entities(detectEntitiesList) - // .allowRegexList(allowRegexList) - // .restrictRegexList(restrictRegexList) - .tokenFormat(tokenFormat) - // .transformations(transformations) - .build(); - - - DeidentifyTextResponse deidentifyTextResponse = skyflowClient.detect(blitzConfig.getVaultId()).deidentifyText(deidentifyTextRequest); - - System.out.println("Deidentify text Response (Vault1): " + deidentifyTextResponse); - } catch (SkyflowException e) { - System.err.println("Error occurred during deidentify (Vault1): "); - e.printStackTrace(); - } - // Example 2: Deidentify text on the second vault - try { - // Create a deidentify text request for the second vault - DeidentifyTextRequest deidentifyTextRequest2 = DeidentifyTextRequest.builder() - .text("My SSN is 123-45-6789 and my card is 4111 1111 1111 1111.") // Replace with the text you want to deidentify - .entities(detectEntitiesList) - // .allowRegexList(allowRegexList) - // .restrictRegexList(restrictRegexList) - .tokenFormat(tokenFormat) - // .transformations(transformations) - .build(); - - DeidentifyTextResponse deidentifyTextResponse2 = skyflowClient.detect(stageConfig.getVaultId()).deidentifyText(deidentifyTextRequest2); - System.out.println("Deidentify text Response (Vault2): " + deidentifyTextResponse2); - - } catch (SkyflowException e) { - System.err.println("Error occurred during deidentify (Vault2): "); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/skyvault/samples/src/main/java/com/example/detect/GetDetectRunExample.java b/skyvault/samples/src/main/java/com/example/detect/GetDetectRunExample.java deleted file mode 100644 index a8f7f39d..00000000 --- a/skyvault/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.ERROR) // Set log level to ERROR - .addVaultConfig(vaultConfig) // Add the vault configuration - .build(); - - try { - // Step 4: Create a get detect run request - GetDetectRunRequest getDetectRunRequest = GetDetectRunRequest.builder() - .runId("") // Replace with the runId from deidentifyFile call - .build(); - - // Step 5: Call getDetectRun to poll for file processing results - DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect(vaultConfig.getVaultId()).getDetectRun(getDetectRunRequest); - System.out.println("Get Detect Run Response: " + deidentifyFileResponse); - } catch (SkyflowException e) { - System.err.println("Error occurred during get detect run: "); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/skyvault/samples/src/main/java/com/example/detect/GetRunSample.java b/skyvault/samples/src/main/java/com/example/detect/GetRunSample.java new file mode 100644 index 00000000..943c92fb --- /dev/null +++ b/skyvault/samples/src/main/java/com/example/detect/GetRunSample.java @@ -0,0 +1,55 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.GetRunRequest; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +/** + * Retrieves the status and, once complete, the outputs of a file de-identification run submitted + * with deidentifyFile. + */ +public class GetRunSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + try { + GetRunResponse run = skyflowClient.detect().getRun( + GetRunRequest.builder().runId("").build()); // Replace with the run id from deidentifyFile + System.out.println("Status: " + run.getStatus()); + switch (run.getStatus()) { + case SUCCESS: + for (FileOutput output : run.getOutput()) { + // output.getProcessedFile() is base64 or a presigned URL, per run.getOutputType() + System.out.println(output.getProcessedFileType() + " -> " + output.getProcessedFileExtension()); + } + break; + case FAILED: + System.err.println("Run failed: " + run.getMessage()); + break; + default: // QUEUED, IN_PROGRESS, UNKNOWN: poll again later + break; + } + } catch (SkyflowException e) { + System.err.println("Error during getRun:"); + e.printStackTrace(); + } + } +} diff --git a/skyvault/samples/src/main/java/com/example/detect/ReidentifyFileSample.java b/skyvault/samples/src/main/java/com/example/detect/ReidentifyFileSample.java new file mode 100644 index 00000000..443e51dd --- /dev/null +++ b/skyvault/samples/src/main/java/com/example/detect/ReidentifyFileSample.java @@ -0,0 +1,71 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.FileOutput; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.RedactionType; +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.detect.ReidentifyFileResponse; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Base64; +import java.util.Collections; + +/** + * Replaces tokens in a de-identified file with their original values, or with a redacted form + * chosen per entity type. Synchronous: the re-identified file comes back in the response. + */ +public class ReidentifyFileSample { + public static void main(String[] args) throws Exception { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + byte[] content = Files.readAllBytes(Paths.get("")); // e.g. processed-notes.txt + + try { + ReidentifyFileResponse response = skyflowClient.detect().reidentifyFile( + ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64) + .value(Base64.getEncoder().encodeToString(content)) + .dataFormat(FileDataFormat.TXT) + .redactionLevel(Collections.singletonList( + RedactionLevel.builder() + .entityName(EntityType.NAME) + .redactionType(RedactionType.PLAIN_TEXT) + .build())) + .build()); + System.out.println("Status: " + response.getStatus()); + if (response.getStatus() == DetectRunStatus.SUCCESS) { + for (FileOutput output : response.getOutput()) { + // output.getProcessedFile() is base64 or a presigned URL, per response.getOutputType() + byte[] processed = Base64.getDecoder().decode(output.getProcessedFile()); + System.out.println(output.getProcessedFileType() + ": " + processed.length + " bytes"); + } + } + } catch (SkyflowException e) { + System.err.println("Error during reidentifyFile:"); + e.printStackTrace(); + } + } +} diff --git a/skyvault/samples/src/main/java/com/example/detect/ReidentifyStringSample.java b/skyvault/samples/src/main/java/com/example/detect/ReidentifyStringSample.java new file mode 100644 index 00000000..8ba28ba0 --- /dev/null +++ b/skyvault/samples/src/main/java/com/example/detect/ReidentifyStringSample.java @@ -0,0 +1,58 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.RedactionType; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.detect.ReidentifyStringResponse; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +import java.util.Arrays; + +/** + * Replaces tokens in a de-identified string with their original values, or with a redacted form + * chosen per entity type. For a skyvault vault each RedactionLevel names an entityName and a + * redactionType. + */ +public class ReidentifyStringSample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + 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) + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .addSkyflowCredentials(credentials) + .build(); + + try { + ReidentifyStringResponse response = skyflowClient.detect().reidentifyString( + ReidentifyStringRequest.builder() + .text("My name is [NAME_1] and my email is [EMAIL_ADDRESS_1].") + .redactionLevel(Arrays.asList( + RedactionLevel.builder() + .entityName(EntityType.NAME) + .redactionType(RedactionType.PLAIN_TEXT) + .build(), + RedactionLevel.builder() + .entityName(EntityType.EMAIL_ADDRESS) + .redactionType(RedactionType.MASKED) + .build())) + .build()); + System.out.println("Processed text: " + response.getProcessedText()); + } catch (SkyflowException e) { + System.err.println("Error during reidentifyString:"); + e.printStackTrace(); + } + } +} diff --git a/skyvault/samples/src/main/java/com/example/detect/ReidentifyTextExample.java b/skyvault/samples/src/main/java/com/example/detect/ReidentifyTextExample.java deleted file mode 100644 index a06a2e62..00000000 --- a/skyvault/samples/src/main/java/com/example/detect/ReidentifyTextExample.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.example.detect; - -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.ReidentifyTextRequest; -import com.skyflow.vault.detect.ReidentifyTextResponse; - -import java.util.ArrayList; -import java.util.List; - -/** - * Skyflow Reidentify Text Example - * - * Demonstrates how to use the Skyflow SDK to reidentify (restore) sensitive values - * in a previously deidentified text string. This is the reverse of deidentifyText. - * - * Steps: - * 1. Configure credentials and vault. - * 2. Create a Skyflow client. - * 3. Build a ReidentifyTextRequest with the deidentified text and entity-display options. - * 4. Call reidentifyText and handle the response. - */ -public class ReidentifyTextExample { - - public static void main(String[] args) throws SkyflowException { - - // Step 1: Set up credentials - Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with path to your credentials JSON file - // Alternative authentication options (uncomment one if needed): - // credentials.setApiKey(""); - // credentials.setToken(""); - // credentials.setCredentialsString(""); - - // Step 2: Configure the vault - VaultConfig vaultConfig = new VaultConfig(); - vaultConfig.setVaultId(""); // Replace with your vault ID - vaultConfig.setClusterId(""); // Replace with your cluster ID (from vault URL) - vaultConfig.setEnv(Env.PROD); // Environment: PROD, SANDBOX, STAGE, or DEV - vaultConfig.setCredentials(credentials); // Attach credentials to this vault - - // Step 3: Create a Skyflow client - Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.ERROR) // Log level: DEBUG, INFO, WARN, ERROR, or OFF - .addVaultConfig(vaultConfig) // Add vault configuration - .build(); - - try { - // Step 4: Configure entity display options for the reidentified output. - // Entities NOT listed in any option list are reidentified to plain text by default. - - // PLAIN TEXT: Return the original sensitive value for these entities - List plainTextEntities = new ArrayList<>(); - plainTextEntities.add(DetectEntities.SSN); // Replace with entities you want in plain text - - // MASKED: Return a masked version of the value (e.g., XXX-XX-6789) - List maskedEntities = new ArrayList<>(); - maskedEntities.add(DetectEntities.CREDIT_CARD); // Replace with entities you want masked - - // REDACTED: Replace entity value with a redaction placeholder - // List redactedEntities = new ArrayList<>(); - // redactedEntities.add(DetectEntities.DOB); // Replace with entities you want redacted - - // Step 5: Build the ReidentifyTextRequest - // The `text` field should be the output of a prior deidentifyText call — - // it contains placeholder tokens like [SSN_IWdexZe] that will be resolved. - ReidentifyTextRequest reidentifyTextRequest = ReidentifyTextRequest.builder() - .text("My SSN is [SSN_IWdexZe] and my card is [CREDIT_CARD_rUzMjdQ].") // Replace with your deidentified text - .plainTextEntities(plainTextEntities) // Restore these as plain text - .maskedEntities(maskedEntities) // Restore these as masked values - // .redactedEntities(redactedEntities) // Restore these as redacted placeholders - .build(); - - // Step 6: Call reidentifyText on the vault - ReidentifyTextResponse reidentifyTextResponse = skyflowClient - .detect("") // Replace with your vault ID - .reidentifyText(reidentifyTextRequest); - - // Step 7: Print the processed text - System.out.println("Reidentify Text Response: " + reidentifyTextResponse); - - // To access the processed text string directly: - // System.out.println("Processed text: " + reidentifyTextResponse.getProcessedText()); - - } catch (SkyflowException e) { - System.err.println("Error occurred during reidentify text:"); - e.printStackTrace(); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/Skyflow.java b/skyvault/src/main/java/com/skyflow/Skyflow.java index 940f5008..8343c4fd 100644 --- a/skyvault/src/main/java/com/skyflow/Skyflow.java +++ b/skyvault/src/main/java/com/skyflow/Skyflow.java @@ -5,10 +5,13 @@ import com.skyflow.config.VaultConfig; import com.skyflow.enums.LogLevel; import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.BaseErrorMessage; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.Constants; +import com.skyflow.utils.SdkVersion; import com.skyflow.utils.Utils; import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; @@ -32,6 +35,8 @@ protected Skyflow self() { } public static SkyflowClientBuilder builder() { + // Keep common's BaseErrorMessage prefix in step with this SDK's own ErrorMessage prefix. + SdkVersion.setSdkPrefix(Constants.SDK_PREFIX); return new SkyflowClientBuilder(); } @@ -99,27 +104,27 @@ public Skyflow updateLogLevel(LogLevel logLevel) { } public VaultController vault() throws SkyflowException { - return resolveOrThrow(this.builder.vaultClientsMap, null, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, ErrorMessage.VaultIdNotInConfigList); + return resolveOrThrow(this.builder.vaultClientsMap, null, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); } public VaultController vault(String vaultId) throws SkyflowException { - return resolveOrThrow(this.builder.vaultClientsMap, vaultId, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, ErrorMessage.VaultIdNotInConfigList); + return resolveOrThrow(this.builder.vaultClientsMap, vaultId, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); } public ConnectionController connection() throws SkyflowException { - return resolveOrThrow(this.builder.connectionsMap, null, ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST, ErrorMessage.ConnectionIdNotInConfigList); + return resolveOrThrow(this.builder.connectionsMap, null, ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.ConnectionIdNotInConfigList); } public ConnectionController connection(String connectionId) throws SkyflowException { - return resolveOrThrow(this.builder.connectionsMap, connectionId, ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST, ErrorMessage.ConnectionIdNotInConfigList); + return resolveOrThrow(this.builder.connectionsMap, connectionId, ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.ConnectionIdNotInConfigList); } public DetectController detect() throws SkyflowException { - return resolveOrThrow(this.builder.detectClientsMap, null, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, ErrorMessage.VaultIdNotInConfigList); + return resolveOrThrow(this.builder.detectClientsMap, null, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); } public DetectController detect(String vaultId) throws SkyflowException { - return resolveOrThrow(this.builder.detectClientsMap, vaultId, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, ErrorMessage.VaultIdNotInConfigList); + return resolveOrThrow(this.builder.detectClientsMap, vaultId, ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST, BaseErrorMessage.VaultIdNotInConfigList); } public static final class SkyflowClientBuilder extends BaseSkyflowClientBuilder { @@ -144,11 +149,18 @@ protected void onVaultConfigAdded(VaultConfig vaultConfig) throws SkyflowExcepti @Override protected void onVaultConfigUpdated(VaultConfig updatedConfig) throws SkyflowException { this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultConfig(updatedConfig); + DetectController detect = this.detectClientsMap.get(updatedConfig.getVaultId()); + if (detect == null) { + this.detectClientsMap.put(updatedConfig.getVaultId(), new DetectController(updatedConfig, this.skyflowCredentials)); + } else { + detect.setVaultConfig(updatedConfig); + } } @Override protected void onVaultConfigRemoved(String vaultId) throws SkyflowException { this.vaultClientsMap.remove(vaultId); + this.detectClientsMap.remove(vaultId); } @Override diff --git a/skyvault/src/main/java/com/skyflow/VaultClient.java b/skyvault/src/main/java/com/skyflow/VaultClient.java index 509b70c7..99301026 100644 --- a/skyvault/src/main/java/com/skyflow/VaultClient.java +++ b/skyvault/src/main/java/com/skyflow/VaultClient.java @@ -2,8 +2,6 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.DetectEntities; -import com.skyflow.enums.DetectOutputTranscriptions; import com.skyflow.enums.InterfaceName; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; @@ -11,30 +9,28 @@ import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.ApiClientBuilder; import com.skyflow.generated.rest.resources.files.FilesClient; -import com.skyflow.generated.rest.resources.files.requests.*; -import com.skyflow.generated.rest.resources.files.types.*; import com.skyflow.generated.rest.resources.query.QueryClient; import com.skyflow.generated.rest.resources.records.RecordsClient; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; -import com.skyflow.generated.rest.resources.strings.StringsClient; -import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; -import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; -import com.skyflow.generated.rest.resources.strings.types.DeidentifyStringRequestEntityTypesItem; +import com.skyflow.generated.rest.resources.records.requests.BatchOperationRequest; +import com.skyflow.generated.rest.resources.records.requests.InsertRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.UpdateRecordRequest; +import com.skyflow.generated.rest.resources.records.types.InsertRecordRequestByot; +import com.skyflow.generated.rest.resources.records.types.UpdateRecordRequestByot; import com.skyflow.generated.rest.resources.tokens.TokensClient; -import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; -import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; -import com.skyflow.generated.rest.types.Transformations; -import com.skyflow.generated.rest.types.*; +import com.skyflow.generated.rest.resources.tokens.requests.DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.TokenizePayload; +import com.skyflow.generated.rest.types.BatchRecord; +import com.skyflow.generated.rest.types.BatchRecordMethod; +import com.skyflow.generated.rest.types.DetokenizeRecordRequest; +import com.skyflow.generated.rest.types.DetokenizeRecordRequestRedaction; +import com.skyflow.generated.rest.types.FieldRecords; +import com.skyflow.generated.rest.types.TokenizeRecordRequest; import com.skyflow.logs.ErrorLogs; import com.skyflow.utils.Utils; import com.skyflow.utils.logger.LogUtil; import com.skyflow.vault.data.FileUploadRequest; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; -import com.skyflow.vault.detect.DeidentifyFileRequest; -import com.skyflow.vault.detect.*; import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; @@ -76,18 +72,14 @@ protected TokensClient getTokensApi() { return this.apiClient.tokens(); } - protected StringsClient getDetectTextApi() { - return this.apiClient.strings(); + protected QueryClient getQueryApi() { + return this.apiClient.query(); } - protected FilesClient getDetectFileAPi() { + protected FilesClient getFilesApi() { return this.apiClient.files(); } - protected QueryClient getQueryApi() { - return this.apiClient.query(); - } - protected void setCommonCredentials(Credentials commonCredentials) throws SkyflowException { this.commonCredentials = commonCredentials; super.prioritiseCredentials(this.vaultConfig.getCredentials()); @@ -103,55 +95,55 @@ protected void updateVaultConfig(VaultConfig newConfig) throws SkyflowException updateVaultConfig(); } - protected V1DetokenizePayload getDetokenizePayload(DetokenizeRequest request) { - List recordRequests = new ArrayList<>(); + protected DetokenizePayload getDetokenizePayload(DetokenizeRequest request) { + List recordRequests = new ArrayList<>(); for (DetokenizeData detokenizeDataRecord : request.getDetokenizeData()) { - V1DetokenizeRecordRequest recordRequest = V1DetokenizeRecordRequest.builder() + DetokenizeRecordRequest recordRequest = DetokenizeRecordRequest.builder() .token(detokenizeDataRecord.getToken()) - .redaction(detokenizeDataRecord.getRedactionType().getRedaction()) + .redaction(DetokenizeRecordRequestRedaction.valueOf(detokenizeDataRecord.getRedactionType().toString())) .build(); recordRequests.add(recordRequest); } - return V1DetokenizePayload.builder() + return DetokenizePayload.builder() .continueOnError(request.getContinueOnError()) .downloadUrl(request.getDownloadUrl()) .detokenizationParameters(recordRequests) .build(); } - protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest request) { + protected InsertRecordRequest getBulkInsertRequestBody(InsertRequest request) { List> values = request.getValues(); List> tokens = request.getTokens(); - List records = new ArrayList<>(); + List records = new ArrayList<>(); for (int index = 0; index < values.size(); index++) { - V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder().fields(values.get(index)); + FieldRecords.Builder recordBuilder = FieldRecords.builder().fields(values.get(index)); if (tokens != null && index < tokens.size()) { recordBuilder.tokens(tokens.get(index)); } records.add(recordBuilder.build()); } - return RecordServiceInsertRecordBody.builder() + return InsertRecordRequest.builder() .tokenization(request.getReturnTokens()) .homogeneous(request.getHomogeneous()) .upsert(request.getUpsert()) - .byot(request.getTokenMode().getByot()) + .byot(InsertRecordRequestByot.valueOf(request.getTokenMode().toString())) .records(records) .build(); } - protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertRequest request) { + protected BatchOperationRequest getBatchInsertRequestBody(InsertRequest request) { ArrayList> values = request.getValues(); ArrayList> tokens = request.getTokens(); - List records = new ArrayList<>(); + List records = new ArrayList<>(); for (int index = 0; index < values.size(); index++) { - V1BatchRecord.Builder recordBuilder = V1BatchRecord.builder() - .method(BatchRecordMethod.POST) + BatchRecord._FinalStage recordBuilder = BatchRecord.builder() .tableName(request.getTable()) + .method(BatchRecordMethod.POST) .upsert(request.getUpsert()) .tokenization(request.getReturnTokens()) .fields(values.get(index)); @@ -163,18 +155,20 @@ protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertReques records.add(recordBuilder.build()); } - return RecordServiceBatchOperationBody.builder() + // The regenerated batch-operation request has no byot field; keep sending it as before so the + // BYOT behaviour of insert(continueOnError=true) is unchanged. + return BatchOperationRequest.builder() .continueOnError(true) - .byot(request.getTokenMode().getByot()) .records(records) + .additionalProperty("byot", request.getTokenMode().toString()) .build(); } - protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest request) { - RecordServiceUpdateRecordBody.Builder updateRequestBodyBuilder = RecordServiceUpdateRecordBody.builder(); - updateRequestBodyBuilder.byot(request.getTokenMode().getByot()); + protected UpdateRecordRequest getUpdateRequestBody(UpdateRequest request) { + UpdateRecordRequest.Builder updateRequestBodyBuilder = UpdateRecordRequest.builder(); + updateRequestBodyBuilder.byot(UpdateRecordRequestByot.valueOf(request.getTokenMode().toString())); updateRequestBodyBuilder.tokenization(request.getReturnTokens()); - V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder(); + FieldRecords.Builder recordBuilder = FieldRecords.builder(); HashMap values = request.getData(); if (values != null) { @@ -191,11 +185,11 @@ protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest reque return updateRequestBodyBuilder.build(); } - protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { - List tokenizationParameters = new ArrayList<>(); + protected TokenizePayload getTokenizePayload(TokenizeRequest request) { + List tokenizationParameters = new ArrayList<>(); for (ColumnValue columnValue : request.getColumnValues()) { - V1TokenizeRecordRequest.Builder recordBuilder = V1TokenizeRecordRequest.builder(); + TokenizeRecordRequest.Builder recordBuilder = TokenizeRecordRequest.builder(); String value = columnValue.getValue(); recordBuilder.value(value); String columnGroup = columnValue.getColumnGroup(); @@ -203,13 +197,9 @@ protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { tokenizationParameters.add(recordBuilder.build()); } - V1TokenizePayload.Builder payloadBuilder = V1TokenizePayload.builder(); - - if (!tokenizationParameters.isEmpty()) { - payloadBuilder.tokenizationParameters(tokenizationParameters); - } - - return payloadBuilder.build(); + return TokenizePayload.builder() + .tokenizationParameters(tokenizationParameters) + .build(); } protected File getFileForFileUpload(FileUploadRequest fileUploadRequest) throws IOException { @@ -234,593 +224,6 @@ protected void setBearerToken() throws SkyflowException { } } - protected DeidentifyTextResponse getDeIdentifyTextResponse(DeidentifyStringResponse deidentifyStringResponse) { - Optional> detectedEntities = deidentifyStringResponse.getEntities(); - - List entities = new ArrayList<>(); - - if (detectedEntities.isPresent()) { - for (StringResponseEntities e : detectedEntities.get()) { - entities.add(convertDetectedEntityToEntityInfo(e)); - } - } - - return new DeidentifyTextResponse( - deidentifyStringResponse.getProcessedText().get(), - entities, - deidentifyStringResponse.getWordCount().get(), - deidentifyStringResponse.getCharacterCount().get() - ); - } - - protected DeidentifyStringRequest getDeidentifyStringRequest(DeidentifyTextRequest deIdentifyTextRequest, String vaultId) throws SkyflowException { - List entities = deIdentifyTextRequest.getEntities(); - - List mappedEntityTypes = null; - if (entities != null) { - mappedEntityTypes = deIdentifyTextRequest.getEntities().stream() - .map(detectEntity -> DeidentifyStringRequestEntityTypesItem.valueOf(detectEntity.name())) - .collect(Collectors.toList()); - } - - TokenFormat tokenFormat = deIdentifyTextRequest.getTokenFormat(); - - Optional> vaultToken = Optional.empty(); - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(deIdentifyTextRequest.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(deIdentifyTextRequest.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(deIdentifyTextRequest.getTransformations())); - - if (tokenFormat != null) { - if (tokenFormat.getVaultToken() != null && !tokenFormat.getVaultToken().isEmpty()) { - vaultToken = Optional.of( - tokenFormat.getVaultToken().stream() - .map(detectEntity -> TokenTypeMappingVaultTokenItem.valueOf(detectEntity.name())) - .collect(Collectors.toList()) - ); - } - - - if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { - entityTypes = Optional.of( - tokenFormat.getEntityOnly().stream() - .map(detectEntity -> TokenTypeMappingEntityOnlyItem.valueOf(detectEntity.name())) - .collect(Collectors.toList()) - ); - } - - - if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { - entityUniqueCounter = Optional.of( - tokenFormat.getEntityUniqueCounter().stream() - .map(detectEntity -> TokenTypeMappingEntityUnqCounterItem.valueOf(detectEntity.name())) - .collect(Collectors.toList()) - ); - } - - } - - TokenTypeMapping tokenType = TokenTypeMapping.builder() - .vaultToken(vaultToken) - .entityOnly(entityTypes) - .entityUnqCounter(entityUniqueCounter) - .build(); - - - return DeidentifyStringRequest.builder() - .text(deIdentifyTextRequest.getText()) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .transformations(transformations) - .build(); - } - - protected ReidentifyStringRequest getReidentifyStringRequest(ReidentifyTextRequest reidentifyTextRequest, String vaultId) throws SkyflowException { - Optional> maskEntities = null; - Optional> redactedEntities = null; - Optional> plaintextEntities = null; - - if (reidentifyTextRequest.getMaskedEntities() != null) { - maskEntities = Optional.of(reidentifyTextRequest.getMaskedEntities().stream() - .map(detectEntity -> FormatMaskedItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - - if (reidentifyTextRequest.getPlainTextEntities() != null) { - plaintextEntities = Optional.of(reidentifyTextRequest.getPlainTextEntities().stream() - .map(detectEntity -> FormatPlaintextItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - - if (reidentifyTextRequest.getRedactedEntities() != null) { - redactedEntities = Optional.of(reidentifyTextRequest.getRedactedEntities().stream() - .map(detectEntity -> FormatRedactedItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - - Format reidentifyStringRequestFormat = Format.builder() - .masked(maskEntities) - .plaintext(plaintextEntities) - .redacted(redactedEntities) - .build(); - - - return ReidentifyStringRequest.builder() - .text(reidentifyTextRequest.getText()) - .vaultId(vaultId) - .format(reidentifyStringRequestFormat) - .build(); - } - - - private EntityInfo convertDetectedEntityToEntityInfo(StringResponseEntities detectedEntity) { - TextIndex textIndex = new TextIndex( - detectedEntity.getLocation().get().getStartIndex().orElse(0), - detectedEntity.getLocation().get().getEndIndex().orElse(0) - ); - TextIndex processedIndex = new TextIndex( - detectedEntity.getLocation().get().getStartIndexProcessed().orElse(0), - detectedEntity.getLocation().get().getEndIndexProcessed().orElse(0) - ); - - Map entityScores = detectedEntity.getEntityScores() - .map(doubleMap -> doubleMap.entrySet().stream() - .collect(Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue - ))) - .orElse(Collections.emptyMap()); - - - return new EntityInfo( - detectedEntity.getToken().orElse(""), - detectedEntity.getValue().orElse(""), - textIndex, - processedIndex, - detectedEntity.getEntityType().orElse(""), - entityScores); - } - - - private Transformations getTransformations(com.skyflow.vault.detect.Transformations transformations) { - if (transformations == null || transformations.getShiftDates() == null) { - return null; - } - - Optional> entityTypes = null; - if (!transformations.getShiftDates().getEntities().isEmpty()) { - entityTypes = Optional.of(transformations.getShiftDates().getEntities().stream() - .map(entity -> ShiftDatesEntityTypesItem.valueOf(entity.name())) - .collect(Collectors.toList())); - } else { - entityTypes = Optional.of(Collections.emptyList()); - } - - return Transformations.builder() - .shiftDates(ShiftDates.builder() - .maxDays(transformations.getShiftDates().getMax()) - .minDays(transformations.getShiftDates().getMin()) - .entityTypes(entityTypes) - .build()) - .build(); - } - - private > List getEntityTypes(List entities, Class type) { - if (entities == null) return Collections.emptyList(); - - return entities.stream() - .map(e -> Enum.valueOf(type, e.name())) - .collect(Collectors.toList()); - } - - - protected com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequestDeidentifyText getDeidentifyTextFileRequest(DeidentifyFileRequest request, String vaultId, String base64Content) { - List mappedEntityTypes = getEntityTypes(request.getEntities(), DeidentifyFileRequestDeidentifyTextEntityTypesItem.class); - - TokenFormat tokenFormat = request.getTokenFormat(); - - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); - - if (tokenFormat != null) { - - if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { - entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() - .map(detectEntity -> TokenTypeMappingEntityOnlyItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - - if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { - entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() - .map(detectEntity -> TokenTypeMappingEntityUnqCounterItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - } - - TokenTypeMapping tokenType = TokenTypeMapping.builder() - .entityOnly(entityTypes) - .entityUnqCounter(entityUniqueCounter) - .build(); - - FileDataDeidentifyText file = FileDataDeidentifyText.builder() - .base64(base64Content) - .build(); - - // Build the final request - com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequestDeidentifyText req = - com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequestDeidentifyText.builder() - .file(file) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .transformations(transformations) - .build(); - - return req; - } - - - protected DeidentifyFileAudioRequestDeidentifyAudio getDeidentifyAudioRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String dataFormat) throws SkyflowException { - List mappedEntityTypes = getEntityTypes(request.getEntities(), DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem.class); - - TokenFormat tokenFormat = request.getTokenFormat(); - - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); - - if (tokenFormat != null) { - if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { - entityTypes = Optional.of( - tokenFormat.getEntityOnly().stream() - .map(detectEntity -> DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem.valueOf(detectEntity.name())) - .collect(Collectors.toList()) - ).map(list -> (List) (List) list); - } - - - if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { - entityUniqueCounter = Optional.of( - (List) (List) - tokenFormat.getEntityUniqueCounter().stream() - .map(detectEntity -> DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem.valueOf(detectEntity.name())) - .collect(Collectors.toList()) - ); - } - - } - - TokenTypeMapping tokenType = TokenTypeMapping.builder() - .entityOnly(entityTypes) - .entityUnqCounter(entityUniqueCounter) - .build(); - - FileDataDeidentifyAudio deidentifyAudioRequestFile = FileDataDeidentifyAudio.builder().base64(base64Content).dataFormat(mapAudioDataFormat(dataFormat)).build(); - DetectOutputTranscriptions transcription = request.getOutputTranscription(); - Optional outputTranscriptionType = null; - if (transcription != null) { - outputTranscriptionType = Optional.of(DeidentifyFileAudioRequestDeidentifyAudioOutputTranscription.valueOf(transcription.name())); - } - - return DeidentifyFileAudioRequestDeidentifyAudio.builder() - .file(deidentifyAudioRequestFile) - .vaultId(vaultId) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .entityTypes(mappedEntityTypes) - .bleepFrequency(request.getBleep() != null - ? (int) Math.round(request.getBleep().getFrequency()) - : null) - .bleepGain(request.getBleep() != null ? (int) Math.round(request.getBleep().getGain()) : null) - .bleepStartPadding(request.getBleep() != null ? (float) Math.round(request.getBleep().getStartPadding()) : null) - .bleepStopPadding(request.getBleep() != null ? (float) Math.round(request.getBleep().getStopPadding()) : null) - .outputProcessedAudio(request.getOutputProcessedAudio()) - .outputTranscription(outputTranscriptionType) - .tokenType(tokenType) - .transformations(transformations) - .build(); - } - - protected DeidentifyFileDocumentPdfRequestDeidentifyPdf getDeidentifyPdfRequest(DeidentifyFileRequest request, String vaultId, String base64Content) { - List mappedEntityTypes = getEntityTypes(request.getEntities(), DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem.class); - - TokenFormat tokenFormat = request.getTokenFormat(); - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - - if (tokenFormat != null) { - if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { - entityTypes = Optional.of( - (List) (List) - tokenFormat.getEntityOnly().stream() - .map(detectEntity -> DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem.valueOf(detectEntity.name())) - .collect(Collectors.toList()) - ); - } - - if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { - entityUniqueCounter = Optional.of( - (List) (List) - tokenFormat.getEntityUniqueCounter().stream() - .map(detectEntity -> DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem.valueOf(detectEntity.name())) - .collect(Collectors.toList()) - ); - } - - } - - TokenTypeMapping tokenType = TokenTypeMapping.builder() - .entityOnly(entityTypes) - .entityUnqCounter(entityUniqueCounter) - .build(); - - FileDataDeidentifyPdf file = FileDataDeidentifyPdf.builder() - .base64(base64Content) - .build(); - - return DeidentifyFileDocumentPdfRequestDeidentifyPdf.builder() - .file(file) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .build(); - } - - protected DeidentifyFileImageRequestDeidentifyImage getDeidentifyImageRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { - List mappedEntityTypes = getEntityTypes(request.getEntities(), DeidentifyFileImageRequestDeidentifyImageEntityTypesItem.class); - - TokenFormat tokenFormat = request.getTokenFormat(); - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - - TokenTypeMapping tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); - - FileDataDeidentifyImage file = FileDataDeidentifyImage.builder() - .base64(base64Content) - .dataFormat(FileDataDeidentifyImageDataFormat.valueOf(format.toUpperCase())) - .build(); - - Optional maskingMethod = Optional.empty(); - if (request.getMaskingMethod() != null) { - maskingMethod = Optional.of(DeidentifyFileImageRequestDeidentifyImageMaskingMethod.valueOf(request.getMaskingMethod().name())); - } - - return DeidentifyFileImageRequestDeidentifyImage.builder() - .file(file) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .maskingMethod(maskingMethod) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .outputProcessedImage(request.getOutputProcessedImage()) - .outputOcrText(request.getOutputOcrText()) - .build(); - } - - protected DeidentifyFileRequestDeidentifyPresentation getDeidentifyPresentationRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { - List mappedEntityTypes = getEntityTypes(request.getEntities(), DeidentifyFileRequestDeidentifyPresentationEntityTypesItem.class); - TokenFormat tokenFormat = request.getTokenFormat(); - - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - - TokenTypeMapping tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); - - FileDataDeidentifyPresentation file = FileDataDeidentifyPresentation.builder() - .base64(base64Content) - .dataFormat(FileDataDeidentifyPresentationDataFormat.valueOf(format.toUpperCase())) - .build(); - - return DeidentifyFileRequestDeidentifyPresentation.builder() - .file(file) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .build(); - } - - protected DeidentifyFileRequestDeidentifySpreadsheet getDeidentifySpreadsheetRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { - List mappedEntityTypes = getEntityTypes(request.getEntities(), DeidentifyFileRequestDeidentifySpreadsheetEntityTypesItem.class); - TokenFormat tokenFormat = request.getTokenFormat(); - - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - - TokenTypeMapping tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); - - FileDataDeidentifySpreadsheet file = FileDataDeidentifySpreadsheet.builder() - .base64(base64Content) - .dataFormat(FileDataDeidentifySpreadsheetDataFormat.valueOf(format.toUpperCase())) - .build(); - - return DeidentifyFileRequestDeidentifySpreadsheet.builder() - .file(file) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .build(); - } - - protected DeidentifyFileRequestDeidentifyStructuredText getDeidentifyStructuredTextRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { - List mappedEntityTypes = getEntityTypes(request.getEntities(), DeidentifyFileRequestDeidentifyStructuredTextEntityTypesItem.class); - TokenFormat tokenFormat = request.getTokenFormat(); - - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); - - TokenTypeMapping tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); - - FileDataDeidentifyStructuredText file = FileDataDeidentifyStructuredText.builder() - .base64(base64Content) - .dataFormat(FileDataDeidentifyStructuredTextDataFormat.valueOf(format.toUpperCase())) - .build(); - - return DeidentifyFileRequestDeidentifyStructuredText.builder() - .file(file) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .transformations(transformations) - .build(); - } - - protected DeidentifyFileRequestDeidentifyDocument getDeidentifyDocumentRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { - List mappedEntityTypes = - getEntityTypes(request.getEntities(), DeidentifyFileRequestDeidentifyDocumentEntityTypesItem.class); - TokenFormat tokenFormat = request.getTokenFormat(); - - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - - TokenTypeMapping tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); - - FileDataDeidentifyDocument file = FileDataDeidentifyDocument.builder() - .base64(base64Content) - .dataFormat(FileDataDeidentifyDocumentDataFormat.valueOf(format.toUpperCase())) - .build(); - - return DeidentifyFileRequestDeidentifyDocument.builder() - .file(file) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .build(); - } - - protected com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest getDeidentifyGenericFileRequest( - DeidentifyFileRequest request, String vaultId, String base64Content, String fileExtension) throws SkyflowException { - - List mappedEntityTypes = - getEntityTypes(request.getEntities(), DeidentifyFileRequestEntityTypesItem.class); - - TokenFormat tokenFormat = request.getTokenFormat(); - - Optional> entityTypes = Optional.empty(); - Optional> entityUniqueCounter = Optional.empty(); - Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); - Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); - - if (tokenFormat != null) { - if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { - entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() - .map(detectEntity -> TokenTypeMappingEntityOnlyItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - - if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { - entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() - .map(detectEntity -> TokenTypeMappingEntityUnqCounterItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - } - - TokenTypeMapping tokenType = TokenTypeMapping.builder() - .entityOnly(entityTypes) - .entityUnqCounter(entityUniqueCounter) - .build(); - - FileDataDataFormat dataFormat = null; - if (fileExtension != null) { - try { - dataFormat = FileDataDataFormat.valueOf(fileExtension.toUpperCase()); - } catch (IllegalArgumentException e) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.UNSUPPORTED_FILE_TYPE_TO_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName(), fileExtension)); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( - ErrorMessage.UnsupportedFileTypeToDeidentify.getMessage(), fileExtension)); - } - } - - FileData file = - FileData.builder() - .base64(base64Content) - .dataFormat(dataFormat) - .build(); - - return com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest.builder() - .file(file) - .vaultId(vaultId) - .entityTypes(mappedEntityTypes) - .tokenType(tokenType) - .allowRegex(allowRegex) - .restrictRegex(restrictRegex) - .transformations(transformations) - .build(); - } - - private TokenTypeMapping buildTokenType(TokenFormat tokenFormat, - Optional> entityTypes, - Optional> entityUniqueCounter) { - - if (tokenFormat != null) { - if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { - entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() - .map(detectEntity -> TokenTypeMappingEntityOnlyItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - - if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { - entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() - .map(detectEntity -> TokenTypeMappingEntityUnqCounterItem.valueOf(detectEntity.name())) - .collect(Collectors.toList())); - } - } - - return TokenTypeMapping.builder() - .entityOnly(entityTypes) - .entityUnqCounter(entityUniqueCounter) - .build(); - - } - - - private FileDataDeidentifyAudioDataFormat mapAudioDataFormat(String dataFormat) throws SkyflowException { - switch (dataFormat) { - case "mp3": - return FileDataDeidentifyAudioDataFormat.MP_3; - case "wav": - return FileDataDeidentifyAudioDataFormat.WAV; - default: - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidAudioFileType.getMessage()); - } - } - private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); if (!vaultURL.equals(this.currentVaultURL)) { diff --git a/skyvault/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java b/skyvault/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java deleted file mode 100644 index 87ffc109..00000000 --- a/skyvault/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.skyflow.enums; - -public enum DeidentifyFileStatus { - IN_PROGRESS("IN_PROGRESS"), - FAILED("FAILED"), - SUCCESS("SUCCESS"), - UNKNOWN("UNKNOWN"); - - private final String value; - - DeidentifyFileStatus(String value) { - this.value = value; - } - - public String value() { - return value; - } -} \ No newline at end of file diff --git a/skyvault/src/main/java/com/skyflow/enums/DetectEntities.java b/skyvault/src/main/java/com/skyflow/enums/DetectEntities.java deleted file mode 100644 index 3fd15a67..00000000 --- a/skyvault/src/main/java/com/skyflow/enums/DetectEntities.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.skyflow.enums; - - -public enum DetectEntities { - ACCOUNT_NUMBER("account_number"), - AGE("age"), - ALL("all"), - BANK_ACCOUNT("bank_account"), - BLOOD_TYPE("blood_type"), - CONDITION("condition"), - CORPORATE_ACTION("corporate_action"), - CREDIT_CARD("credit_card"), - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - CVV("cvv"), - DATE("date"), - DAY("day"), - DATE_INTERVAL("date_interval"), - DOB("dob"), - DOSE("dose"), - DRIVER_LICENSE("driver_license"), - DRUG("drug"), - DURATION("duration"), - EFFECT("effect"), - EMAIL_ADDRESS("email_address"), - EVENT("event"), - FILENAME("filename"), - FINANCIAL_METRIC("financial_metric"), - GENDER("gender"), - HEALTHCARE_NUMBER("healthcare_number"), - INJURY("injury"), - IP_ADDRESS("ip_address"), - LANGUAGE("language"), - LOCATION("location"), - LOCATION_ADDRESS("location_address"), - LOCATION_ADDRESS_STREET("location_address_street"), - LOCATION_CITY("location_city"), - LOCATION_COORDINATE("location_coordinate"), - LOCATION_COUNTRY("location_country"), - LOCATION_STATE("location_state"), - LOCATION_ZIP("location_zip"), - MARITAL_STATUS("marital_status"), - MEDICAL_CODE("medical_code"), - MEDICAL_PROCESS("medical_process"), - MONEY("money"), - MONTH("month"), - NAME("name"), - NAME_FAMILY("name_family"), - NAME_GIVEN("name_given"), - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - NUMERICAL_PII("numerical_pii"), - OCCUPATION("occupation"), - ORGANIZATION("organization"), - ORGANIZATION_ID("organization_id"), - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - ORIGIN("origin"), - PASSPORT_NUMBER("passport_number"), - PASSWORD("password"), - PHONE_NUMBER("phone_number"), - PROJECT("project"), - PHYSICAL_ATTRIBUTE("physical_attribute"), - POLITICAL_AFFILIATION("political_affiliation"), - PRODUCT("product"), - RELIGION("religion"), - ROUTING_NUMBER("routing_number"), - SEXUALITY("sexuality"), - SSN("ssn"), - STATISTICS("statistics"), - TIME("time"), - TREND("trend"), - URL("url"), - USERNAME("username"), - VEHICLE_ID("vehicle_id"), - YEAR("year"), - ZODIAC_SIGN("zodiac_sign"); - - private final String detectEntities; - - DetectEntities(String detectEntities) { - this.detectEntities = detectEntities; - } - - public String getDetectEntities() { - return detectEntities; - } - - @Override - public String toString() { - return detectEntities; - } -} diff --git a/skyvault/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java b/skyvault/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java deleted file mode 100644 index 8d0c42a4..00000000 --- a/skyvault/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.skyflow.enums; - -public enum DetectOutputTranscriptions { - DIARIZED_TRANSCRIPTION("diarized_transcription"), - MEDICAL_DIARIZED_TRANSCRIPTION("medical_diarized_transcription"), - MEDICAL_TRANSCRIPTION("medical_transcription"), - TRANSCRIPTION("transcription"); - - private final String detectOutputTranscriptions; - - DetectOutputTranscriptions(String detectOutputTranscriptions) { - this.detectOutputTranscriptions = detectOutputTranscriptions; - } - - public String getDetectOutputTranscriptions() { - return detectOutputTranscriptions; - } - - @Override - public String toString() { - return detectOutputTranscriptions; - } -} diff --git a/skyvault/src/main/java/com/skyflow/enums/MaskingMethod.java b/skyvault/src/main/java/com/skyflow/enums/MaskingMethod.java deleted file mode 100644 index e3ff252c..00000000 --- a/skyvault/src/main/java/com/skyflow/enums/MaskingMethod.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.skyflow.enums; - -public enum MaskingMethod { - BLACKBOX("blackbox"), - BLUR("blur"); - - private final String maskingMethod; - - MaskingMethod(String maskingMethod) { - this.maskingMethod = maskingMethod; - } - - public String getMaskingMethod() { - return maskingMethod; - } - - @Override - public String toString() { - return maskingMethod; - } -} diff --git a/skyvault/src/main/java/com/skyflow/enums/TokenType.java b/skyvault/src/main/java/com/skyflow/enums/TokenType.java deleted file mode 100644 index 4a619e9c..00000000 --- a/skyvault/src/main/java/com/skyflow/enums/TokenType.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.skyflow.enums; - -public enum TokenType { - VAULT_TOKEN("vault_token"), - ENTITY_UNIQUE_COUNTER("entity_unq_counter"), - ENTITY_ONLY("entity_only"); - - private final String tokenType; - - TokenType(String tokenType) { - this.tokenType = tokenType; - } - - public String getTokenType() { - return tokenType; - } - - public String getDefault() { - return ENTITY_UNIQUE_COUNTER.getTokenType(); - } - - @Override - public String toString() { - return tokenType; - } -} - diff --git a/skyvault/src/main/java/com/skyflow/errors/ErrorMessage.java b/skyvault/src/main/java/com/skyflow/errors/ErrorMessage.java index 6e7419a9..d49a4641 100644 --- a/skyvault/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/skyvault/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -147,33 +147,7 @@ public enum ErrorMessage { InvalidFileObject("%s0 Validation error. Invalid file object in file upload request. Specify a valid file object."), InvalidBase64("%s0 Validation error. Invalid base64 string in file upload request. Specify a valid base64 string."), - // detect - DeidentifyTextRequestNull("%s0 Validation error. DeidentifyTextRequest object is null. Specify a valid DeidentifyTextRequest object."), - InvalidTextInDeIdentify("%s0 Validation error. The text field is required and must be a non-empty string. Specify a valid text."), - ReidentifyTextRequestNull("%s0 Validation error. ReidentifyTextRequest object is null. Specify a valid ReidentifyTextRequest object."), - InvalidTextInReIdentify("%s0 Validation error. The text field is required and must be a non-empty string. Specify a valid text."), - - //Detect Files - InvalidNullFileInDeIdentifyFile("%s0 Validation error. The file field is required and must not be null. Specify a valid file object."), InvalidFilePath("%s0 Validation error. The file path is invalid. Specify a valid file path."), - BothFileAndFilePathProvided("%s0 Validation error. Both file and filePath are provided. Specify either file object or filePath, not both."), - FileNotFoundToDeidentify("%s0 Validation error. The file to deidentify was not found at the specified path. Verify the file path and try again."), - FileNotReadableToDeidentify("%s0 Validation error. The file to deidentify is not readable. Check the file permissions and try again."), - InvalidPixelDensityToDeidentifyFile("%s0 Validation error. Should be a positive integer. Specify a valid pixel density."), - InvalidMaxResolution("%s0 Validation error. Should be a positive integer. Specify a valid max resolution."), - OutputDirectoryNotFound("%s0 Validation error. The output directory for deidentified files was not found at the specified path. Verify the output directory path and try again."), - InvalidPermission("%s0 Validation error. The output directory for deidentified files is not writable. Check the directory permissions and try again."), - InvalidWaitTime("%s0 Validation error. The wait time for deidentify file operation should be a positive integer. Specify a valid wait time."), - WaitTimeExceedsLimit("%s0 Validation error. The wait time for deidentify file operation exceeds the maximum limit of 64 seconds. Specify a wait time less than or equal to 60 seconds."), - InvalidOrEmptyRunId("%s0 Validation error. The run ID is invalid or empty. Specify a valid run ID."), - FailedToEncodeFile("%s0 Validation error. Failed to encode the file. Ensure the file is in a supported format and try again."), - FailedToDecodeFileFromResponse("%s0 Failed to decode the file from the response. Ensure the response is valid and try again."), - EmptyFileAndFilePathInDeIdentifyFile("%s0 Validation error. Both file and filePath are empty. Specify either file object or filePath, not both."), - VaultTokenFormatIsNotAllowedForFiles("%s0 Validation error. Vault token format is not allowed for deidentify file request."), - PollingForResultsFailed("%s0 API error. Polling for results failed. Unable to retrieve the deidentified file"), - FailedToSaveProcessedFile("%s0 Validation error. Failed to save the processed file. Ensure the output directory is valid and writable."), - InvalidAudioFileType("%s0 Validation error. The file type is not supported. Specify a valid file type mp3 or wav."), - UnsupportedFileTypeToDeidentify("%s0 Validation error. File type '%s1' is not supported for deidentification. Specify a supported file type."), // Generic ErrorOccurred("%s0 API error. Error occurred.") ; diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/ApiClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/ApiClient.java index ab81f443..e59a5e6f 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/ApiClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/ApiClient.java @@ -4,24 +4,20 @@ package com.skyflow.generated.rest; import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; import com.skyflow.generated.rest.core.Suppliers; -import com.skyflow.generated.rest.resources.audit.AuditClient; -import com.skyflow.generated.rest.resources.binlookup.BinLookupClient; +import com.skyflow.generated.rest.requests.PatchV2VaultsIdRequest; import com.skyflow.generated.rest.resources.files.FilesClient; -import com.skyflow.generated.rest.resources.guardrails.GuardrailsClient; import com.skyflow.generated.rest.resources.query.QueryClient; import com.skyflow.generated.rest.resources.records.RecordsClient; -import com.skyflow.generated.rest.resources.strings.StringsClient; import com.skyflow.generated.rest.resources.tokens.TokensClient; - +import java.util.Optional; import java.util.function.Supplier; -public class ApiClient { +public class ApiClient implements AutoCloseable { protected final ClientOptions clientOptions; - protected final Supplier auditClient; - - protected final Supplier binLookupClient; + private final RawApiClient rawClient; protected final Supplier recordsClient; @@ -31,28 +27,37 @@ public class ApiClient { protected final Supplier filesClient; - protected final Supplier stringsClient; - - protected final Supplier guardrailsClient; - public ApiClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.auditClient = Suppliers.memoize(() -> new AuditClient(clientOptions)); - this.binLookupClient = Suppliers.memoize(() -> new BinLookupClient(clientOptions)); + this.rawClient = new RawApiClient(clientOptions); this.recordsClient = Suppliers.memoize(() -> new RecordsClient(clientOptions)); this.tokensClient = Suppliers.memoize(() -> new TokensClient(clientOptions)); this.queryClient = Suppliers.memoize(() -> new QueryClient(clientOptions)); this.filesClient = Suppliers.memoize(() -> new FilesClient(clientOptions)); - this.stringsClient = Suppliers.memoize(() -> new StringsClient(clientOptions)); - this.guardrailsClient = Suppliers.memoize(() -> new GuardrailsClient(clientOptions)); } - public AuditClient audit() { - return this.auditClient.get(); + /** + * Get responses with HTTP metadata like headers + */ + public RawApiClient withRawResponse() { + return this.rawClient; + } + + public void patchV2VaultsId(Optional vaultId) { + this.rawClient.patchV2VaultsId(vaultId).body(); } - public BinLookupClient binLookup() { - return this.binLookupClient.get(); + public void patchV2VaultsId(Optional vaultId, RequestOptions requestOptions) { + this.rawClient.patchV2VaultsId(vaultId, requestOptions).body(); + } + + public void patchV2VaultsId(Optional vaultId, PatchV2VaultsIdRequest request) { + this.rawClient.patchV2VaultsId(vaultId, request).body(); + } + + public void patchV2VaultsId( + Optional vaultId, PatchV2VaultsIdRequest request, RequestOptions requestOptions) { + this.rawClient.patchV2VaultsId(vaultId, request, requestOptions).body(); } public RecordsClient records() { @@ -71,12 +76,13 @@ public FilesClient files() { return this.filesClient.get(); } - public StringsClient strings() { - return this.stringsClient.get(); - } - - public GuardrailsClient guardrails() { - return this.guardrailsClient.get(); + /** + * Releases resources owned by this client. See {@code ClientOptions.close()} for what is + * and is not released. + */ + @Override + public void close() { + this.clientOptions.close(); } public static ApiClientBuilder builder() { diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java b/skyvault/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java index 4f8f5f78..18cee274 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java @@ -5,15 +5,35 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.Environment; +import com.skyflow.generated.rest.core.LogConfig; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import okhttp3.OkHttpClient; -public final class ApiClientBuilder { - private ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder(); +public class ApiClientBuilder { + private Optional timeout = Optional.empty(); + + private Optional maxRetries = Optional.empty(); + + private Optional initialRetryDelayMillis = Optional.empty(); + + private Optional maxRetryDelayMillis = Optional.empty(); + + private Optional retryJitterFactor = Optional.empty(); + + private final Map customHeaders = new HashMap<>(); private String token = null; private Environment environment = Environment.PRODUCTION; + private OkHttpClient httpClient; + + private Optional logging = Optional.empty(); + + private String identifier; + /** * Sets token */ @@ -36,7 +56,7 @@ public ApiClientBuilder url(String url) { * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. */ public ApiClientBuilder timeout(int timeout) { - this.clientOptionsBuilder.timeout(timeout); + this.timeout = Optional.of(timeout); return this; } @@ -44,7 +64,31 @@ public ApiClientBuilder timeout(int timeout) { * Sets the maximum number of retries for the client. Defaults to 2 retries. */ public ApiClientBuilder maxRetries(int maxRetries) { - this.clientOptionsBuilder.maxRetries(maxRetries); + this.maxRetries = Optional.of(maxRetries); + return this; + } + + /** + * Sets the initial delay (in milliseconds) used for exponential backoff between retries. Defaults to 1000 milliseconds. + */ + public ApiClientBuilder initialRetryDelayMillis(long initialRetryDelayMillis) { + this.initialRetryDelayMillis = Optional.of(initialRetryDelayMillis); + return this; + } + + /** + * Sets the maximum delay (in milliseconds) between retries. Defaults to 60000 milliseconds. + */ + public ApiClientBuilder maxRetryDelayMillis(long maxRetryDelayMillis) { + this.maxRetryDelayMillis = Optional.of(maxRetryDelayMillis); + return this; + } + + /** + * Sets the jitter factor (between 0 and 1) applied to retry delays. Defaults to 0.2. + */ + public ApiClientBuilder retryJitterFactor(double retryJitterFactor) { + this.retryJitterFactor = Optional.of(retryJitterFactor); return this; } @@ -52,13 +96,191 @@ public ApiClientBuilder maxRetries(int maxRetries) { * Sets the underlying OkHttp client */ public ApiClientBuilder httpClient(OkHttpClient httpClient) { - this.clientOptionsBuilder.httpClient(httpClient); + this.httpClient = httpClient; + return this; + } + + /** + * Configure logging for the SDK. Silent by default — no log output unless explicitly configured. + */ + public ApiClientBuilder logging(LogConfig logging) { + this.logging = Optional.of(logging); + return this; + } + + /** + * Add a custom header to be sent with all requests. + * For headers that need to be computed dynamically or conditionally, use the setAdditional() method override instead. + * + * @param name The header name + * @param value The header value + * @return This builder for method chaining + */ + public ApiClientBuilder addHeader(String name, String value) { + this.customHeaders.put(name, value); + return this; + } + + public ApiClientBuilder identifier(String identifier) { + this.identifier = identifier; return this; } + protected ClientOptions buildClientOptions() { + ClientOptions.Builder builder = ClientOptions.builder(); + setEnvironment(builder); + setAuthentication(builder); + setHttpClient(builder); + setTimeouts(builder); + setRetries(builder); + setLogging(builder); + for (Map.Entry header : this.customHeaders.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } + setAdditional(builder); + return builder.build(); + } + + /** + * Sets the environment configuration for the client. + * Override this method to modify URLs or add environment-specific logic. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setEnvironment(ClientOptions.Builder builder) { + if (this.identifier != null) { + String _identifier = this.identifier != null ? this.identifier : "{{vault_uri}}"; + String _urlTemplate = null; + if (this.environment == null) { + _urlTemplate = "https://{identifier}.vault.skyflowapis.com"; + } else if (this.environment.equals(Environment.PRODUCTION)) { + _urlTemplate = "https://{identifier}.vault.skyflowapis.com"; + } else if (this.environment.equals(Environment.SANDBOX)) { + _urlTemplate = "https://{identifier}.vault.skyflowapis-preview.com"; + } + if (_urlTemplate != null) { + this.environment = Environment.custom(_urlTemplate.replace("{identifier}", _identifier)); + } + } + builder.environment(this.environment); + } + + /** + * Override this method to customize authentication. + * This method is called during client options construction to set up authentication headers. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *

{@code
+     * @Override
+     * protected void setAuthentication(ClientOptions.Builder builder) {
+     *     super.setAuthentication(builder); // Keep existing auth
+     *     builder.addHeader("X-API-Key", this.apiKey);
+     * }
+     * }
+ */ + protected void setAuthentication(ClientOptions.Builder builder) { + if (this.token != null) { + builder.addHeader("Authorization", "Bearer " + this.token); + } + } + + /** + * Sets the request timeout configuration. + * Override this method to customize timeout behavior. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setTimeouts(ClientOptions.Builder builder) { + if (this.timeout.isPresent()) { + builder.timeout(this.timeout.get()); + } + } + + /** + * Sets the retry configuration for failed requests. + * Override this method to implement custom retry strategies. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setRetries(ClientOptions.Builder builder) { + if (this.maxRetries.isPresent()) { + builder.maxRetries(this.maxRetries.get()); + } + if (this.initialRetryDelayMillis.isPresent()) { + builder.initialRetryDelayMillis(this.initialRetryDelayMillis.get()); + } + if (this.maxRetryDelayMillis.isPresent()) { + builder.maxRetryDelayMillis(this.maxRetryDelayMillis.get()); + } + if (this.retryJitterFactor.isPresent()) { + builder.retryJitterFactor(this.retryJitterFactor.get()); + } + } + + /** + * Sets the OkHttp client configuration. + * Override this method to customize HTTP client behavior (interceptors, connection pools, etc). + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setHttpClient(ClientOptions.Builder builder) { + if (this.httpClient != null) { + builder.httpClient(this.httpClient); + } + } + + /** + * Sets the logging configuration for the SDK. + * Override this method to customize logging behavior. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setLogging(ClientOptions.Builder builder) { + if (this.logging.isPresent()) { + builder.logging(this.logging.get()); + } + } + + /** + * Override this method to add any additional configuration to the client. + * This method is called at the end of the configuration chain, allowing you to add + * custom headers, modify settings, or perform any other client customization. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+     * @Override
+     * protected void setAdditional(ClientOptions.Builder builder) {
+     *     builder.addHeader("X-Request-ID", () -> UUID.randomUUID().toString());
+     *     builder.addHeader("X-Client-Version", "1.0.0");
+     * }
+     * }
+ */ + protected void setAdditional(ClientOptions.Builder builder) {} + + /** + * Override this method to add custom validation logic before the client is built. + * This method is called at the beginning of the build() method to ensure the configuration is valid. + * Throw an exception to prevent client creation if validation fails. + * + * Example: + *
{@code
+     * @Override
+     * protected void validateConfiguration() {
+     *     super.validateConfiguration(); // Run parent validations
+     *     if (tenantId == null || tenantId.isEmpty()) {
+     *         throw new IllegalStateException("tenantId is required");
+     *     }
+     * }
+     * }
+ */ + protected void validateConfiguration() {} + public ApiClient build() { - this.clientOptionsBuilder.addHeader("Authorization", "Bearer " + this.token); - clientOptionsBuilder.environment(this.environment); - return new ApiClient(clientOptionsBuilder.build()); + validateConfiguration(); + return new ApiClient(buildClientOptions()); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java index dc57df06..cb5c6188 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java @@ -4,24 +4,21 @@ package com.skyflow.generated.rest; import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; import com.skyflow.generated.rest.core.Suppliers; -import com.skyflow.generated.rest.resources.audit.AsyncAuditClient; -import com.skyflow.generated.rest.resources.binlookup.AsyncBinLookupClient; +import com.skyflow.generated.rest.requests.PatchV2VaultsIdRequest; import com.skyflow.generated.rest.resources.files.AsyncFilesClient; -import com.skyflow.generated.rest.resources.guardrails.AsyncGuardrailsClient; import com.skyflow.generated.rest.resources.query.AsyncQueryClient; import com.skyflow.generated.rest.resources.records.AsyncRecordsClient; -import com.skyflow.generated.rest.resources.strings.AsyncStringsClient; import com.skyflow.generated.rest.resources.tokens.AsyncTokensClient; - +import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; -public class AsyncApiClient { +public class AsyncApiClient implements AutoCloseable { protected final ClientOptions clientOptions; - protected final Supplier auditClient; - - protected final Supplier binLookupClient; + private final AsyncRawApiClient rawClient; protected final Supplier recordsClient; @@ -31,28 +28,37 @@ public class AsyncApiClient { protected final Supplier filesClient; - protected final Supplier stringsClient; - - protected final Supplier guardrailsClient; - public AsyncApiClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.auditClient = Suppliers.memoize(() -> new AsyncAuditClient(clientOptions)); - this.binLookupClient = Suppliers.memoize(() -> new AsyncBinLookupClient(clientOptions)); + this.rawClient = new AsyncRawApiClient(clientOptions); this.recordsClient = Suppliers.memoize(() -> new AsyncRecordsClient(clientOptions)); this.tokensClient = Suppliers.memoize(() -> new AsyncTokensClient(clientOptions)); this.queryClient = Suppliers.memoize(() -> new AsyncQueryClient(clientOptions)); this.filesClient = Suppliers.memoize(() -> new AsyncFilesClient(clientOptions)); - this.stringsClient = Suppliers.memoize(() -> new AsyncStringsClient(clientOptions)); - this.guardrailsClient = Suppliers.memoize(() -> new AsyncGuardrailsClient(clientOptions)); } - public AsyncAuditClient audit() { - return this.auditClient.get(); + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawApiClient withRawResponse() { + return this.rawClient; + } + + public CompletableFuture patchV2VaultsId(Optional vaultId) { + return this.rawClient.patchV2VaultsId(vaultId).thenApply(response -> response.body()); } - public AsyncBinLookupClient binLookup() { - return this.binLookupClient.get(); + public CompletableFuture patchV2VaultsId(Optional vaultId, RequestOptions requestOptions) { + return this.rawClient.patchV2VaultsId(vaultId, requestOptions).thenApply(response -> response.body()); + } + + public CompletableFuture patchV2VaultsId(Optional vaultId, PatchV2VaultsIdRequest request) { + return this.rawClient.patchV2VaultsId(vaultId, request).thenApply(response -> response.body()); + } + + public CompletableFuture patchV2VaultsId( + Optional vaultId, PatchV2VaultsIdRequest request, RequestOptions requestOptions) { + return this.rawClient.patchV2VaultsId(vaultId, request, requestOptions).thenApply(response -> response.body()); } public AsyncRecordsClient records() { @@ -71,12 +77,13 @@ public AsyncFilesClient files() { return this.filesClient.get(); } - public AsyncStringsClient strings() { - return this.stringsClient.get(); - } - - public AsyncGuardrailsClient guardrails() { - return this.guardrailsClient.get(); + /** + * Releases resources owned by this client. See {@code ClientOptions.close()} for what is + * and is not released. + */ + @Override + public void close() { + this.clientOptions.close(); } public static AsyncApiClientBuilder builder() { diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java b/skyvault/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java index 55a1c518..76fd8d42 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java @@ -5,15 +5,35 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.Environment; +import com.skyflow.generated.rest.core.LogConfig; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import okhttp3.OkHttpClient; -public final class AsyncApiClientBuilder { - private ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder(); +public class AsyncApiClientBuilder { + private Optional timeout = Optional.empty(); + + private Optional maxRetries = Optional.empty(); + + private Optional initialRetryDelayMillis = Optional.empty(); + + private Optional maxRetryDelayMillis = Optional.empty(); + + private Optional retryJitterFactor = Optional.empty(); + + private final Map customHeaders = new HashMap<>(); private String token = null; private Environment environment = Environment.PRODUCTION; + private OkHttpClient httpClient; + + private Optional logging = Optional.empty(); + + private String identifier; + /** * Sets token */ @@ -36,7 +56,7 @@ public AsyncApiClientBuilder url(String url) { * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. */ public AsyncApiClientBuilder timeout(int timeout) { - this.clientOptionsBuilder.timeout(timeout); + this.timeout = Optional.of(timeout); return this; } @@ -44,7 +64,31 @@ public AsyncApiClientBuilder timeout(int timeout) { * Sets the maximum number of retries for the client. Defaults to 2 retries. */ public AsyncApiClientBuilder maxRetries(int maxRetries) { - this.clientOptionsBuilder.maxRetries(maxRetries); + this.maxRetries = Optional.of(maxRetries); + return this; + } + + /** + * Sets the initial delay (in milliseconds) used for exponential backoff between retries. Defaults to 1000 milliseconds. + */ + public AsyncApiClientBuilder initialRetryDelayMillis(long initialRetryDelayMillis) { + this.initialRetryDelayMillis = Optional.of(initialRetryDelayMillis); + return this; + } + + /** + * Sets the maximum delay (in milliseconds) between retries. Defaults to 60000 milliseconds. + */ + public AsyncApiClientBuilder maxRetryDelayMillis(long maxRetryDelayMillis) { + this.maxRetryDelayMillis = Optional.of(maxRetryDelayMillis); + return this; + } + + /** + * Sets the jitter factor (between 0 and 1) applied to retry delays. Defaults to 0.2. + */ + public AsyncApiClientBuilder retryJitterFactor(double retryJitterFactor) { + this.retryJitterFactor = Optional.of(retryJitterFactor); return this; } @@ -52,13 +96,191 @@ public AsyncApiClientBuilder maxRetries(int maxRetries) { * Sets the underlying OkHttp client */ public AsyncApiClientBuilder httpClient(OkHttpClient httpClient) { - this.clientOptionsBuilder.httpClient(httpClient); + this.httpClient = httpClient; + return this; + } + + /** + * Configure logging for the SDK. Silent by default — no log output unless explicitly configured. + */ + public AsyncApiClientBuilder logging(LogConfig logging) { + this.logging = Optional.of(logging); + return this; + } + + /** + * Add a custom header to be sent with all requests. + * For headers that need to be computed dynamically or conditionally, use the setAdditional() method override instead. + * + * @param name The header name + * @param value The header value + * @return This builder for method chaining + */ + public AsyncApiClientBuilder addHeader(String name, String value) { + this.customHeaders.put(name, value); + return this; + } + + public AsyncApiClientBuilder identifier(String identifier) { + this.identifier = identifier; return this; } + protected ClientOptions buildClientOptions() { + ClientOptions.Builder builder = ClientOptions.builder(); + setEnvironment(builder); + setAuthentication(builder); + setHttpClient(builder); + setTimeouts(builder); + setRetries(builder); + setLogging(builder); + for (Map.Entry header : this.customHeaders.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } + setAdditional(builder); + return builder.build(); + } + + /** + * Sets the environment configuration for the client. + * Override this method to modify URLs or add environment-specific logic. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setEnvironment(ClientOptions.Builder builder) { + if (this.identifier != null) { + String _identifier = this.identifier != null ? this.identifier : "{{vault_uri}}"; + String _urlTemplate = null; + if (this.environment == null) { + _urlTemplate = "https://{identifier}.vault.skyflowapis.com"; + } else if (this.environment.equals(Environment.PRODUCTION)) { + _urlTemplate = "https://{identifier}.vault.skyflowapis.com"; + } else if (this.environment.equals(Environment.SANDBOX)) { + _urlTemplate = "https://{identifier}.vault.skyflowapis-preview.com"; + } + if (_urlTemplate != null) { + this.environment = Environment.custom(_urlTemplate.replace("{identifier}", _identifier)); + } + } + builder.environment(this.environment); + } + + /** + * Override this method to customize authentication. + * This method is called during client options construction to set up authentication headers. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+     * @Override
+     * protected void setAuthentication(ClientOptions.Builder builder) {
+     *     super.setAuthentication(builder); // Keep existing auth
+     *     builder.addHeader("X-API-Key", this.apiKey);
+     * }
+     * }
+ */ + protected void setAuthentication(ClientOptions.Builder builder) { + if (this.token != null) { + builder.addHeader("Authorization", "Bearer " + this.token); + } + } + + /** + * Sets the request timeout configuration. + * Override this method to customize timeout behavior. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setTimeouts(ClientOptions.Builder builder) { + if (this.timeout.isPresent()) { + builder.timeout(this.timeout.get()); + } + } + + /** + * Sets the retry configuration for failed requests. + * Override this method to implement custom retry strategies. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setRetries(ClientOptions.Builder builder) { + if (this.maxRetries.isPresent()) { + builder.maxRetries(this.maxRetries.get()); + } + if (this.initialRetryDelayMillis.isPresent()) { + builder.initialRetryDelayMillis(this.initialRetryDelayMillis.get()); + } + if (this.maxRetryDelayMillis.isPresent()) { + builder.maxRetryDelayMillis(this.maxRetryDelayMillis.get()); + } + if (this.retryJitterFactor.isPresent()) { + builder.retryJitterFactor(this.retryJitterFactor.get()); + } + } + + /** + * Sets the OkHttp client configuration. + * Override this method to customize HTTP client behavior (interceptors, connection pools, etc). + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setHttpClient(ClientOptions.Builder builder) { + if (this.httpClient != null) { + builder.httpClient(this.httpClient); + } + } + + /** + * Sets the logging configuration for the SDK. + * Override this method to customize logging behavior. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setLogging(ClientOptions.Builder builder) { + if (this.logging.isPresent()) { + builder.logging(this.logging.get()); + } + } + + /** + * Override this method to add any additional configuration to the client. + * This method is called at the end of the configuration chain, allowing you to add + * custom headers, modify settings, or perform any other client customization. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+     * @Override
+     * protected void setAdditional(ClientOptions.Builder builder) {
+     *     builder.addHeader("X-Request-ID", () -> UUID.randomUUID().toString());
+     *     builder.addHeader("X-Client-Version", "1.0.0");
+     * }
+     * }
+ */ + protected void setAdditional(ClientOptions.Builder builder) {} + + /** + * Override this method to add custom validation logic before the client is built. + * This method is called at the beginning of the build() method to ensure the configuration is valid. + * Throw an exception to prevent client creation if validation fails. + * + * Example: + *
{@code
+     * @Override
+     * protected void validateConfiguration() {
+     *     super.validateConfiguration(); // Run parent validations
+     *     if (tenantId == null || tenantId.isEmpty()) {
+     *         throw new IllegalStateException("tenantId is required");
+     *     }
+     * }
+     * }
+ */ + protected void validateConfiguration() {} + public AsyncApiClient build() { - this.clientOptionsBuilder.addHeader("Authorization", "Bearer " + this.token); - clientOptionsBuilder.environment(this.environment); - return new AsyncApiClient(clientOptionsBuilder.build()); + validateConfiguration(); + return new AsyncApiClient(buildClientOptions()); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/AsyncRawApiClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/AsyncRawApiClient.java new file mode 100644 index 00000000..da58025b --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/AsyncRawApiClient.java @@ -0,0 +1,110 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; +import com.skyflow.generated.rest.requests.PatchV2VaultsIdRequest; +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawApiClient { + protected final ClientOptions clientOptions; + + public AsyncRawApiClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + public CompletableFuture> patchV2VaultsId(Optional vaultId) { + return patchV2VaultsId(vaultId, PatchV2VaultsIdRequest.builder().build()); + } + + public CompletableFuture> patchV2VaultsId( + Optional vaultId, RequestOptions requestOptions) { + return patchV2VaultsId(vaultId, PatchV2VaultsIdRequest.builder().build(), requestOptions); + } + + public CompletableFuture> patchV2VaultsId( + Optional vaultId, PatchV2VaultsIdRequest request) { + return patchV2VaultsId(vaultId, request, null); + } + + public CompletableFuture> patchV2VaultsId( + Optional vaultId, PatchV2VaultsIdRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/vaults"); + if (vaultId.isPresent()) { + httpUrl.addPathSegment(vaultId.get()); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/RawApiClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/RawApiClient.java new file mode 100644 index 00000000..a39d00ca --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/RawApiClient.java @@ -0,0 +1,90 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; +import com.skyflow.generated.rest.requests.PatchV2VaultsIdRequest; +import java.io.IOException; +import java.util.Optional; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawApiClient { + protected final ClientOptions clientOptions; + + public RawApiClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + public ApiClientHttpResponse patchV2VaultsId(Optional vaultId) { + return patchV2VaultsId(vaultId, PatchV2VaultsIdRequest.builder().build()); + } + + public ApiClientHttpResponse patchV2VaultsId(Optional vaultId, RequestOptions requestOptions) { + return patchV2VaultsId(vaultId, PatchV2VaultsIdRequest.builder().build(), requestOptions); + } + + public ApiClientHttpResponse patchV2VaultsId(Optional vaultId, PatchV2VaultsIdRequest request) { + return patchV2VaultsId(vaultId, request, null); + } + + public ApiClientHttpResponse patchV2VaultsId( + Optional vaultId, PatchV2VaultsIdRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/vaults"); + if (vaultId.isPresent()) { + httpUrl.addPathSegment(vaultId.get()); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new ApiClientApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java index be5247eb..c016a435 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java @@ -3,12 +3,11 @@ */ package com.skyflow.generated.rest.core; -import okhttp3.Response; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import okhttp3.Response; /** * This exception type will be thrown for any non-2XX API responses. @@ -68,7 +67,7 @@ public Map> headers() { @Override public String toString() { - return "ApiClientApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + body - + "}"; + return "ApiClientApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + + ObjectMappers.stringify(body) + "}"; } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java index c743352c..9c81f1f5 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java @@ -3,12 +3,11 @@ */ package com.skyflow.generated.rest.core; -import okhttp3.Response; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import okhttp3.Response; public final class ApiClientHttpResponse { diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java index da41fb25..3f3a7dc6 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java @@ -3,13 +3,12 @@ */ package com.skyflow.generated.rest.core; -import okhttp3.OkHttpClient; - import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import okhttp3.OkHttpClient; public final class ClientOptions { private final Environment environment; @@ -20,14 +19,32 @@ public final class ClientOptions { private final OkHttpClient httpClient; + private final boolean ownsHttpClient; + private final int timeout; + private final int maxRetries; + + private final Optional initialRetryDelayMillis; + + private final Optional maxRetryDelayMillis; + + private final Optional retryJitterFactor; + + private final Optional logging; + private ClientOptions( Environment environment, Map headers, Map> headerSuppliers, OkHttpClient httpClient, - int timeout) { + boolean ownsHttpClient, + int timeout, + int maxRetries, + Optional initialRetryDelayMillis, + Optional maxRetryDelayMillis, + Optional retryJitterFactor, + Optional logging) { this.environment = environment; this.headers = new HashMap<>(); this.headers.putAll(headers); @@ -35,12 +52,18 @@ private ClientOptions( { put("X-Fern-Language", "JAVA"); put("X-Fern-SDK-Name", "com.skyflow.fern:api-sdk"); - put("X-Fern-SDK-Version", "0.0.385"); + put("X-Fern-SDK-Version", "0.0.98"); } }); this.headerSuppliers = headerSuppliers; this.httpClient = httpClient; + this.ownsHttpClient = ownsHttpClient; this.timeout = timeout; + this.maxRetries = maxRetries; + this.initialRetryDelayMillis = initialRetryDelayMillis; + this.maxRetryDelayMillis = maxRetryDelayMillis; + this.retryJitterFactor = retryJitterFactor; + this.logging = logging; } public Environment environment() { @@ -82,11 +105,50 @@ public OkHttpClient httpClientWithTimeout(RequestOptions requestOptions) { .build(); } + public int maxRetries() { + return this.maxRetries; + } + + public Optional initialRetryDelayMillis() { + return this.initialRetryDelayMillis; + } + + public Optional maxRetryDelayMillis() { + return this.maxRetryDelayMillis; + } + + public Optional retryJitterFactor() { + return this.retryJitterFactor; + } + + /** + * Releases resources owned by this client. Only shuts down the underlying OkHttpClient's + * dispatcher executor and evicts its connection pool when this client created that + * OkHttpClient itself; an OkHttpClient supplied via httpClient is left running, since the + * caller owns its lifecycle. + *

+ * In-flight calls are not cancelled or awaited, and any request issued after this method + * returns fails with a {@code RejectedExecutionException}. Options derived from this one via + * {@code Builder.from(...)} share the same dispatcher and connection pool, so closing either + * releases them for both. Calling this method more than once has no further effect. + */ + public void close() { + if (!this.ownsHttpClient) { + return; + } + this.httpClient.dispatcher().executorService().shutdown(); + this.httpClient.connectionPool().evictAll(); + } + + public Optional logging() { + return this.logging; + } + public static Builder builder() { return new Builder(); } - public static final class Builder { + public static class Builder { private Environment environment; private final Map headers = new HashMap<>(); @@ -95,17 +157,29 @@ public static final class Builder { private int maxRetries = 2; + private Optional initialRetryDelayMillis = Optional.empty(); + + private Optional maxRetryDelayMillis = Optional.empty(); + + private Optional retryJitterFactor = Optional.empty(); + private Optional timeout = Optional.empty(); private OkHttpClient httpClient = null; + private boolean ownsHttpClient = true; + + private Optional logging = Optional.empty(); + public Builder environment(Environment environment) { this.environment = environment; return this; } public Builder addHeader(String key, String value) { - this.headers.put(key, value); + if (value != null) { + this.headers.put(key, value); + } return this; } @@ -138,8 +212,45 @@ public Builder maxRetries(int maxRetries) { return this; } + /** + * Override the initial delay (in milliseconds) used for exponential backoff between retries. Defaults to 1000 milliseconds. + */ + public Builder initialRetryDelayMillis(long initialRetryDelayMillis) { + this.initialRetryDelayMillis = Optional.of(initialRetryDelayMillis); + return this; + } + + /** + * Override the maximum delay (in milliseconds) between retries. Defaults to 60000 milliseconds. + */ + public Builder maxRetryDelayMillis(long maxRetryDelayMillis) { + this.maxRetryDelayMillis = Optional.of(maxRetryDelayMillis); + return this; + } + + /** + * Override the jitter factor (between 0 and 1) applied to retry delays. Defaults to 0.2. + */ + public Builder retryJitterFactor(double retryJitterFactor) { + this.retryJitterFactor = Optional.of(retryJitterFactor); + return this; + } + + /** + * Sets the underlying OkHttp client. The caller retains ownership of its lifecycle: + * close() will not shut down its dispatcher executor or evict its connection pool. + */ public Builder httpClient(OkHttpClient httpClient) { this.httpClient = httpClient; + this.ownsHttpClient = httpClient == null; + return this; + } + + /** + * Configure logging for the SDK. Silent by default — no log output unless explicitly configured. + */ + public Builder logging(LogConfig logging) { + this.logging = Optional.of(logging); return this; } @@ -159,13 +270,51 @@ public ClientOptions build() { .connectTimeout(0, TimeUnit.SECONDS) .writeTimeout(0, TimeUnit.SECONDS) .readTimeout(0, TimeUnit.SECONDS) - .addInterceptor(new RetryInterceptor(this.maxRetries)); + .addInterceptor(new RetryInterceptor( + this.maxRetries, + this.initialRetryDelayMillis, + this.maxRetryDelayMillis, + this.retryJitterFactor)); } + Logger logger = Logger.from(this.logging); + httpClientBuilder.addInterceptor(new LoggingInterceptor(logger)); + httpClientBuilder.addInterceptor(new ResponseDecompressionInterceptor()); + this.httpClient = httpClientBuilder.build(); this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000); - return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout.get()); + return new ClientOptions( + environment, + headers, + headerSuppliers, + httpClient, + this.ownsHttpClient, + this.timeout.get(), + this.maxRetries, + this.initialRetryDelayMillis, + this.maxRetryDelayMillis, + this.retryJitterFactor, + this.logging); + } + + /** + * Create a new Builder initialized with values from an existing ClientOptions + */ + public static Builder from(ClientOptions clientOptions) { + Builder builder = new Builder(); + builder.environment = clientOptions.environment(); + builder.timeout = Optional.of(clientOptions.timeout(null)); + builder.httpClient = clientOptions.httpClient(); + builder.ownsHttpClient = clientOptions.ownsHttpClient; + builder.headers.putAll(clientOptions.headers); + builder.headerSuppliers.putAll(clientOptions.headerSuppliers); + builder.maxRetries = clientOptions.maxRetries(); + builder.initialRetryDelayMillis = clientOptions.initialRetryDelayMillis(); + builder.maxRetryDelayMillis = clientOptions.maxRetryDelayMillis(); + builder.retryJitterFactor = clientOptions.retryJitterFactor(); + builder.logging = clientOptions.logging(); + return builder; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ConsoleLogger.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ConsoleLogger.java new file mode 100644 index 00000000..d3786dcc --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ConsoleLogger.java @@ -0,0 +1,52 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.logging.Level; + +/** + * Default logger implementation that writes to the console using {@link java.util.logging.Logger}. + * + *

Uses the "fern" logger name with a simple format of "LEVEL - message". + */ +public final class ConsoleLogger implements ILogger { + + private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("fern"); + + static { + if (logger.getHandlers().length == 0) { + java.util.logging.ConsoleHandler handler = new java.util.logging.ConsoleHandler(); + handler.setFormatter(new java.util.logging.SimpleFormatter() { + @Override + public String format(java.util.logging.LogRecord record) { + return record.getLevel() + " - " + record.getMessage() + System.lineSeparator(); + } + }); + handler.setLevel(Level.ALL); + logger.addHandler(handler); + logger.setUseParentHandlers(false); + logger.setLevel(Level.ALL); + } + } + + @Override + public void debug(String message) { + logger.log(Level.FINE, message); + } + + @Override + public void info(String message) { + logger.log(Level.INFO, message); + } + + @Override + public void warn(String message) { + logger.log(Level.WARNING, message); + } + + @Override + public void error(String message) { + logger.log(Level.SEVERE, message); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java index a0a6d7c4..0f422bc2 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java @@ -8,18 +8,19 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.module.SimpleModule; - import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; /** - * Custom deserializer that handles converting ISO8601 dates into {@link OffsetDateTime} objects. + * Custom deserializer that handles converting date-time strings into {@link OffsetDateTime} objects. + * Supports ISO 8601 format, space-separated variants, and RFC 1123 (RFC 2822) format. */ class DateTimeDeserializer extends JsonDeserializer { private static final SimpleModule MODULE; @@ -43,8 +44,21 @@ public OffsetDateTime deserialize(JsonParser parser, DeserializationContext cont if (token == JsonToken.VALUE_NUMBER_INT) { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(parser.getValueAsLong()), ZoneOffset.UTC); } else { - TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest( - parser.getValueAsString(), OffsetDateTime::from, LocalDateTime::from); + String value = parser.getValueAsString(); + TemporalAccessor temporal; + try { + temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(value, OffsetDateTime::from, LocalDateTime::from); + } catch (DateTimeParseException e) { + try { + // Fall back to space-separated format (e.g. "2025-02-15 10:30:00+00:00"). + temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest( + value.replace(' ', 'T'), OffsetDateTime::from, LocalDateTime::from); + } catch (DateTimeParseException e2) { + // Fall back to RFC 1123 format (e.g. "Thu, 07 May 2026 14:23:38 +0000"). + temporal = DateTimeFormatter.RFC_1123_DATE_TIME.parseBest( + value, OffsetDateTime::from, LocalDateTime::from); + } + } if (temporal.query(TemporalQueries.offset()) == null) { return LocalDateTime.from(temporal).atOffset(ZoneOffset.UTC); diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/DoubleSerializer.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/DoubleSerializer.java new file mode 100644 index 00000000..131d0a9a --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/DoubleSerializer.java @@ -0,0 +1,43 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; +import java.io.IOException; + +/** + * Custom serializer that writes integer-valued doubles without a decimal point. + * For example, {@code 24000.0} is serialized as {@code 24000} instead of {@code 24000.0}. + * Non-integer values like {@code 3.14} are serialized normally. + */ +class DoubleSerializer extends JsonSerializer { + private static final SimpleModule MODULE; + + static { + MODULE = new SimpleModule() + .addSerializer(Double.class, new DoubleSerializer()) + .addSerializer(double.class, new DoubleSerializer()); + } + + /** + * Gets a module wrapping this serializer as an adapter for the Jackson ObjectMapper. + * + * @return A {@link SimpleModule} to be plugged onto Jackson ObjectMapper. + */ + public static SimpleModule getModule() { + return MODULE; + } + + @Override + public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + if (value != null && value == Math.floor(value) && !Double.isInfinite(value) && !Double.isNaN(value)) { + gen.writeNumber(value.longValue()); + } else { + gen.writeNumber(value); + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/Environment.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/Environment.java index c0adb233..93e13ce9 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/Environment.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/Environment.java @@ -4,9 +4,10 @@ package com.skyflow.generated.rest.core; public final class Environment { - public static final Environment PRODUCTION = new Environment("https://identifier.vault.skyflowapis.com"); + public static final Environment PRODUCTION = new Environment("https://%7B%7Bvault_uri%7D%7D.vault.skyflowapis.com"); - public static final Environment SANDBOX = new Environment("https://identifier.vault.skyflowapis-preview.com"); + public static final Environment SANDBOX = + new Environment("https://%7B%7Bvault_uri%7D%7D.vault.skyflowapis-preview.com"); private final String url; diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/FileStream.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/FileStream.java index 2131b0a4..6b459431 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/FileStream.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/FileStream.java @@ -3,13 +3,12 @@ */ package com.skyflow.generated.rest.core; +import java.io.InputStream; +import java.util.Objects; import okhttp3.MediaType; import okhttp3.RequestBody; import org.jetbrains.annotations.Nullable; -import java.io.InputStream; -import java.util.Objects; - /** * Represents a file stream with associated metadata for file uploads. */ diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ILogger.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ILogger.java new file mode 100644 index 00000000..a70ec8e6 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ILogger.java @@ -0,0 +1,38 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +/** + * Interface for custom logger implementations. + * + *

Implement this interface to provide a custom logging backend for the SDK. + * The SDK will call the appropriate method based on the log level. + * + *

Example: + *

{@code
+ * public class MyCustomLogger implements ILogger {
+ *     public void debug(String message) {
+ *         System.out.println("[DBG] " + message);
+ *     }
+ *     public void info(String message) {
+ *         System.out.println("[INF] " + message);
+ *     }
+ *     public void warn(String message) {
+ *         System.out.println("[WRN] " + message);
+ *     }
+ *     public void error(String message) {
+ *         System.out.println("[ERR] " + message);
+ *     }
+ * }
+ * }
+ */ +public interface ILogger { + void debug(String message); + + void info(String message); + + void warn(String message); + + void error(String message); +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java index 55c3c971..5351a5f8 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java @@ -3,18 +3,16 @@ */ package com.skyflow.generated.rest.core; +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; import okhttp3.MediaType; import okhttp3.RequestBody; -import okhttp3.internal.Util; import okio.BufferedSink; import okio.Okio; import okio.Source; import org.jetbrains.annotations.Nullable; -import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; - /** * A custom implementation of OkHttp's RequestBody that wraps an InputStream. * This class allows streaming of data from an InputStream directly to an HTTP request body, @@ -69,12 +67,8 @@ public long contentLength() throws IOException { */ @Override public void writeTo(BufferedSink sink) throws IOException { - Source source = null; - try { - source = Okio.source(inputStream); + try (Source source = Okio.source(inputStream)) { sink.writeAll(source); - } finally { - Util.closeQuietly(Objects.requireNonNull(source)); } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/LogConfig.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/LogConfig.java new file mode 100644 index 00000000..7928e097 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/LogConfig.java @@ -0,0 +1,98 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +/** + * Configuration for SDK logging. + * + *

Use the builder to configure logging behavior: + *

{@code
+ * LogConfig config = LogConfig.builder()
+ *     .level(LogLevel.DEBUG)
+ *     .silent(false)
+ *     .build();
+ * }
+ * + *

Or with a custom logger: + *

{@code
+ * LogConfig config = LogConfig.builder()
+ *     .level(LogLevel.DEBUG)
+ *     .logger(new MyCustomLogger())
+ *     .silent(false)
+ *     .build();
+ * }
+ * + *

Defaults: + *

    + *
  • {@code level} — {@link LogLevel#INFO}
  • + *
  • {@code logger} — {@link ConsoleLogger} (writes to stderr via java.util.logging)
  • + *
  • {@code silent} — {@code true} (no output unless explicitly enabled)
  • + *
+ */ +public final class LogConfig { + + private final LogLevel level; + private final ILogger logger; + private final boolean silent; + + private LogConfig(LogLevel level, ILogger logger, boolean silent) { + this.level = level; + this.logger = logger; + this.silent = silent; + } + + public LogLevel level() { + return level; + } + + public ILogger logger() { + return logger; + } + + public boolean silent() { + return silent; + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private LogLevel level = LogLevel.INFO; + private ILogger logger = new ConsoleLogger(); + private boolean silent = true; + + private Builder() {} + + /** + * Set the minimum log level. Only messages at this level or above will be logged. + * Defaults to {@link LogLevel#INFO}. + */ + public Builder level(LogLevel level) { + this.level = level; + return this; + } + + /** + * Set a custom logger implementation. Defaults to {@link ConsoleLogger}. + */ + public Builder logger(ILogger logger) { + this.logger = logger; + return this; + } + + /** + * Set whether logging is silent (disabled). Defaults to {@code true}. + * Set to {@code false} to enable log output. + */ + public Builder silent(boolean silent) { + this.silent = silent; + return this; + } + + public LogConfig build() { + return new LogConfig(level, logger, silent); + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/LogLevel.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/LogLevel.java new file mode 100644 index 00000000..db72cd0a --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/LogLevel.java @@ -0,0 +1,36 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +/** + * Log levels for SDK logging configuration. + * Silent by default — no log output unless explicitly configured. + */ +public enum LogLevel { + DEBUG(1), + INFO(2), + WARN(3), + ERROR(4); + + private final int value; + + LogLevel(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + /** + * Parse a log level from a string (case-insensitive). + * + * @param level the level string (debug, info, warn, error) + * @return the corresponding LogLevel + * @throws IllegalArgumentException if the string does not match any level + */ + public static LogLevel fromString(String level) { + return LogLevel.valueOf(level.toUpperCase()); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/Logger.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/Logger.java new file mode 100644 index 00000000..a5603955 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/Logger.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +/** + * SDK logger that filters messages based on level and silent mode. + * + *

Silent by default — no log output unless explicitly configured. + * Create via {@link LogConfig} or directly: + *

{@code
+ * Logger logger = new Logger(LogLevel.DEBUG, new ConsoleLogger(), false);
+ * logger.debug("request sent");
+ * }
+ */ +public final class Logger { + + private static final Logger DEFAULT = new Logger(LogLevel.INFO, new ConsoleLogger(), true); + + private final LogLevel level; + private final ILogger logger; + private final boolean silent; + + public Logger(LogLevel level, ILogger logger, boolean silent) { + this.level = level; + this.logger = logger; + this.silent = silent; + } + + /** + * Returns a default silent logger (no output). + */ + public static Logger getDefault() { + return DEFAULT; + } + + /** + * Creates a Logger from a {@link LogConfig}. If config is {@code null}, returns the default silent logger. + */ + public static Logger from(LogConfig config) { + if (config == null) { + return DEFAULT; + } + return new Logger(config.level(), config.logger(), config.silent()); + } + + /** + * Creates a Logger from an {@code Optional}. If empty, returns the default silent logger. + */ + public static Logger from(java.util.Optional config) { + return config.map(Logger::from).orElse(DEFAULT); + } + + private boolean shouldLog(LogLevel messageLevel) { + return !silent && level.getValue() <= messageLevel.getValue(); + } + + public boolean isDebug() { + return shouldLog(LogLevel.DEBUG); + } + + public boolean isInfo() { + return shouldLog(LogLevel.INFO); + } + + public boolean isWarn() { + return shouldLog(LogLevel.WARN); + } + + public boolean isError() { + return shouldLog(LogLevel.ERROR); + } + + public void debug(String message) { + if (isDebug()) { + logger.debug(message); + } + } + + public void info(String message) { + if (isInfo()) { + logger.info(message); + } + } + + public void warn(String message) { + if (isWarn()) { + logger.warn(message); + } + } + + public void error(String message) { + if (isError()) { + logger.error(message); + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/LoggingInterceptor.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/LoggingInterceptor.java new file mode 100644 index 00000000..407b7937 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/LoggingInterceptor.java @@ -0,0 +1,104 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +/** + * OkHttp interceptor that logs HTTP requests and responses. + * + *

Logs request method, URL, and headers (with sensitive values redacted) at debug level. + * Logs response status at debug level, and 4xx/5xx responses at error level. + * Does nothing if the logger is silent. + */ +public final class LoggingInterceptor implements Interceptor { + + private static final Set SENSITIVE_HEADERS = new HashSet<>(Arrays.asList( + "authorization", + "www-authenticate", + "x-api-key", + "api-key", + "apikey", + "x-api-token", + "x-auth-token", + "auth-token", + "proxy-authenticate", + "proxy-authorization", + "cookie", + "set-cookie", + "x-csrf-token", + "x-xsrf-token", + "x-session-token", + "x-access-token")); + + private final Logger logger; + + public LoggingInterceptor(Logger logger) { + this.logger = logger; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + if (logger.isDebug()) { + StringBuilder sb = new StringBuilder(); + sb.append("HTTP Request: ").append(request.method()).append(" ").append(request.url()); + sb.append(" headers={"); + boolean first = true; + for (String name : request.headers().names()) { + if (!first) { + sb.append(", "); + } + sb.append(name).append("="); + if (SENSITIVE_HEADERS.contains(name.toLowerCase())) { + sb.append("[REDACTED]"); + } else { + sb.append(request.header(name)); + } + first = false; + } + sb.append("}"); + sb.append(" has_body=").append(request.body() != null); + logger.debug(sb.toString()); + } + + Response response = chain.proceed(request); + + if (logger.isDebug()) { + StringBuilder sb = new StringBuilder(); + sb.append("HTTP Response: status=").append(response.code()); + sb.append(" url=").append(response.request().url()); + sb.append(" headers={"); + boolean first = true; + for (String name : response.headers().names()) { + if (!first) { + sb.append(", "); + } + sb.append(name).append("="); + if (SENSITIVE_HEADERS.contains(name.toLowerCase())) { + sb.append("[REDACTED]"); + } else { + sb.append(response.header(name)); + } + first = false; + } + sb.append("}"); + logger.debug(sb.toString()); + } + + if (response.code() >= 400 && logger.isError()) { + logger.error("HTTP Error: status=" + response.code() + " url=" + + response.request().url()); + } + + return response; + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java index 98c33be4..a6cffd4d 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java @@ -14,6 +14,9 @@ public boolean equals(Object o) { } private boolean isOptionalEmpty(Object o) { - return o instanceof Optional && !((Optional) o).isPresent(); + if (o instanceof Optional) { + return !((Optional) o).isPresent(); + } + return false; } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java index acec32b4..4f69f150 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java @@ -4,13 +4,13 @@ package com.skyflow.generated.rest.core; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - import java.io.IOException; public final class ObjectMappers { @@ -18,6 +18,7 @@ public final class ObjectMappers { .addModule(new Jdk8Module()) .addModule(new JavaTimeModule()) .addModule(DateTimeDeserializer.getModule()) + .addModule(DoubleSerializer.getModule()) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .build(); @@ -34,4 +35,12 @@ public static String stringify(Object o) { return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); } } + + public static Object parseErrorBody(String responseBodyString) { + try { + return JSON_MAPPER.readValue(responseBodyString, Object.class); + } catch (JsonProcessingException ignored) { + return responseBodyString; + } + } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java index c0687736..e9e18fb9 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java @@ -7,11 +7,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import okhttp3.HttpUrl; import okhttp3.MultipartBody; -import java.util.*; - public class QueryStringMapper { private static final ObjectMapper MAPPER = ObjectMappers.JSON_MAPPER; diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java index edc6d0ae..26b396e4 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java @@ -16,21 +16,33 @@ public final class RequestOptions { private final TimeUnit timeoutTimeUnit; + private final Optional maxRetries; + private final Map headers; private final Map> headerSuppliers; + private final Map queryParameters; + + private final Map> queryParameterSuppliers; + private RequestOptions( String token, Optional timeout, TimeUnit timeoutTimeUnit, + Optional maxRetries, Map headers, - Map> headerSuppliers) { + Map> headerSuppliers, + Map queryParameters, + Map> queryParameterSuppliers) { this.token = token; this.timeout = timeout; this.timeoutTimeUnit = timeoutTimeUnit; + this.maxRetries = maxRetries; this.headers = headers; this.headerSuppliers = headerSuppliers; + this.queryParameters = queryParameters; + this.queryParameterSuppliers = queryParameterSuppliers; } public Optional getTimeout() { @@ -41,6 +53,10 @@ public TimeUnit getTimeoutTimeUnit() { return timeoutTimeUnit; } + public Optional getMaxRetries() { + return maxRetries; + } + public Map getHeaders() { Map headers = new HashMap<>(); if (this.token != null) { @@ -53,21 +69,35 @@ public Map getHeaders() { return headers; } + public Map getQueryParameters() { + Map queryParameters = new HashMap<>(this.queryParameters); + this.queryParameterSuppliers.forEach((key, supplier) -> { + queryParameters.put(key, supplier.get()); + }); + return queryParameters; + } + public static Builder builder() { return new Builder(); } - public static final class Builder { + public static class Builder { private String token = null; private Optional timeout = Optional.empty(); private TimeUnit timeoutTimeUnit = TimeUnit.SECONDS; + private Optional maxRetries = Optional.empty(); + private final Map headers = new HashMap<>(); private final Map> headerSuppliers = new HashMap<>(); + private final Map queryParameters = new HashMap<>(); + + private final Map> queryParameterSuppliers = new HashMap<>(); + public Builder token(String token) { this.token = token; return this; @@ -84,6 +114,11 @@ public Builder timeout(Integer timeout, TimeUnit timeoutTimeUnit) { return this; } + public Builder maxRetries(Integer maxRetries) { + this.maxRetries = Optional.of(maxRetries); + return this; + } + public Builder addHeader(String key, String value) { this.headers.put(key, value); return this; @@ -94,8 +129,26 @@ public Builder addHeader(String key, Supplier value) { return this; } + public Builder addQueryParameter(String key, String value) { + this.queryParameters.put(key, value); + return this; + } + + public Builder addQueryParameter(String key, Supplier value) { + this.queryParameterSuppliers.put(key, value); + return this; + } + public RequestOptions build() { - return new RequestOptions(token, timeout, timeoutTimeUnit, headers, headerSuppliers); + return new RequestOptions( + token, + timeout, + timeoutTimeUnit, + maxRetries, + headers, + headerSuppliers, + queryParameters, + queryParameterSuppliers); } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java index 1bb0b5dc..d8df7715 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java @@ -3,10 +3,9 @@ */ package com.skyflow.generated.rest.core; -import okhttp3.Response; - import java.io.FilterInputStream; import java.io.IOException; +import okhttp3.Response; /** * A custom InputStream that wraps the InputStream from the OkHttp Response and ensures that the diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java index e6c1a525..ed894407 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java @@ -3,10 +3,9 @@ */ package com.skyflow.generated.rest.core; -import okhttp3.Response; - import java.io.FilterReader; import java.io.IOException; +import okhttp3.Response; /** * A custom Reader that wraps the Reader from the OkHttp Response and ensures that the diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseDecompressionInterceptor.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseDecompressionInterceptor.java new file mode 100644 index 00000000..d6938347 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/ResponseDecompressionInterceptor.java @@ -0,0 +1,56 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.IOException; +import java.util.zip.Inflater; +import okhttp3.Interceptor; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okio.GzipSource; +import okio.InflaterSource; +import okio.Okio; +import okio.Source; + +/** + * Decompresses gzip and deflate encoded response bodies. OkHttp only performs + * transparent decompression when it adds the Accept-Encoding header itself, so + * responses to requests with an explicitly set Accept-Encoding header would + * otherwise be returned as raw compressed bytes. + */ +public class ResponseDecompressionInterceptor implements Interceptor { + + @Override + public Response intercept(Chain chain) throws IOException { + return decompress(chain.proceed(chain.request())); + } + + private Response decompress(Response response) { + ResponseBody body = response.body(); + if (body == null) { + return response; + } + String encoding = response.header("Content-Encoding"); + if (encoding == null) { + return response; + } + Source decompressedSource; + if (encoding.equalsIgnoreCase("gzip") || encoding.equalsIgnoreCase("x-gzip")) { + decompressedSource = new GzipSource(body.source()); + } else if (encoding.equalsIgnoreCase("deflate")) { + decompressedSource = new InflaterSource(body.source(), new Inflater()); + } else { + return response; + } + ResponseBody decompressedBody = ResponseBody.create(body.contentType(), -1L, Okio.buffer(decompressedSource)); + return response.newBuilder() + .headers(response.headers() + .newBuilder() + .removeAll("Content-Encoding") + .removeAll("Content-Length") + .build()) + .body(decompressedBody) + .build(); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java index 7a28c3c9..7d89751d 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java @@ -3,37 +3,80 @@ */ package com.skyflow.generated.rest.core; -import okhttp3.Interceptor; -import okhttp3.Response; - import java.io.IOException; import java.time.Duration; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.Optional; import java.util.Random; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; public class RetryInterceptor implements Interceptor { - private static final Duration ONE_SECOND = Duration.ofSeconds(1); - private final ExponentialBackoff backoff; + private static final Duration DEFAULT_INITIAL_RETRY_DELAY = Duration.ofMillis(1000); + private static final Duration DEFAULT_MAX_RETRY_DELAY = Duration.ofMillis(60000); + private static final double DEFAULT_JITTER_FACTOR = 0.2; + + private final int maxRetries; + private final Duration initialRetryDelay; + private final Duration maxRetryDelay; + private final double jitterFactor; private final Random random = new Random(); public RetryInterceptor(int maxRetries) { - this.backoff = new ExponentialBackoff(maxRetries); + this(maxRetries, Optional.empty(), Optional.empty(), Optional.empty()); + } + + public RetryInterceptor( + int maxRetries, + Optional initialRetryDelayMillis, + Optional maxRetryDelayMillis, + Optional jitterFactor) { + initialRetryDelayMillis.ifPresent(delay -> { + if (delay < 0) { + throw new IllegalArgumentException("initialRetryDelayMillis must be non-negative"); + } + }); + maxRetryDelayMillis.ifPresent(delay -> { + if (delay < 0) { + throw new IllegalArgumentException("maxRetryDelayMillis must be non-negative"); + } + }); + jitterFactor.ifPresent(factor -> { + if (factor < 0 || factor > 1) { + throw new IllegalArgumentException("jitterFactor must be between 0 and 1"); + } + }); + this.maxRetries = maxRetries; + this.initialRetryDelay = initialRetryDelayMillis.map(Duration::ofMillis).orElse(DEFAULT_INITIAL_RETRY_DELAY); + this.maxRetryDelay = maxRetryDelayMillis.map(Duration::ofMillis).orElse(DEFAULT_MAX_RETRY_DELAY); + this.jitterFactor = jitterFactor.orElse(DEFAULT_JITTER_FACTOR); } @Override public Response intercept(Chain chain) throws IOException { - Response response = chain.proceed(chain.request()); + Request request = chain.request(); + int effectiveMaxRetries = resolveMaxRetries(request); + Response response = chain.proceed(request); if (shouldRetry(response.code())) { - return retryChain(response, chain); + return retryChain(response, chain, effectiveMaxRetries); } return response; } - private Response retryChain(Response response, Chain chain) throws IOException { - Optional nextBackoff = this.backoff.nextBackoff(); + private int resolveMaxRetries(Request request) { + MaxRetriesOverride override = request.tag(MaxRetriesOverride.class); + return override != null ? override.getValue() : this.maxRetries; + } + + private Response retryChain(Response response, Chain chain, int maxRetries) throws IOException { + ExponentialBackoff backoff = new ExponentialBackoff(maxRetries); + Optional nextBackoff = backoff.nextBackoff(response); while (nextBackoff.isPresent()) { try { Thread.sleep(nextBackoff.get().toMillis()); @@ -43,7 +86,7 @@ private Response retryChain(Response response, Chain chain) throws IOException { response.close(); response = chain.proceed(chain.request()); if (shouldRetry(response.code())) { - nextBackoff = this.backoff.nextBackoff(); + nextBackoff = backoff.nextBackoff(response); } else { return response; } @@ -52,10 +95,130 @@ private Response retryChain(Response response, Chain chain) throws IOException { return response; } + /** + * Calculates the retry delay from response headers, with fallback to exponential backoff. + * Priority: Retry-After > X-RateLimit-Reset > Exponential Backoff + */ + private Duration getRetryDelayFromHeaders(Response response, int retryAttempt) { + // Check for Retry-After header first (RFC 7231), with no jitter + String retryAfter = response.header("Retry-After"); + if (retryAfter != null) { + // Parse as number of seconds... + Optional secondsDelay = tryParseLong(retryAfter) + .map(seconds -> seconds * 1000) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, maxRetryDelay.toMillis())) + .map(Duration::ofMillis); + if (secondsDelay.isPresent()) { + return secondsDelay.get(); + } + + // ...or as an HTTP date; both are valid + Optional dateDelay = tryParseHttpDate(retryAfter) + .map(resetTime -> resetTime.toInstant().toEpochMilli() - System.currentTimeMillis()) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, maxRetryDelay.toMillis())) + .map(Duration::ofMillis); + if (dateDelay.isPresent()) { + return dateDelay.get(); + } + } + + // Then check for industry-standard X-RateLimit-Reset header, with positive jitter + String rateLimitReset = response.header("X-RateLimit-Reset"); + if (rateLimitReset != null) { + // Assume Unix timestamp in epoch seconds + Optional rateLimitDelay = tryParseLong(rateLimitReset) + .map(resetTimeSeconds -> (resetTimeSeconds * 1000) - System.currentTimeMillis()) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, maxRetryDelay.toMillis())) + .map(this::addPositiveJitter) + .map(Duration::ofMillis); + if (rateLimitDelay.isPresent()) { + return rateLimitDelay.get(); + } + } + + // Fall back to exponential backoff, with symmetric jitter + long initialDelayMillis = initialRetryDelay.toMillis(); + long maxDelayMillis = maxRetryDelay.toMillis(); + long cappedDelay; + if (retryAttempt >= Long.SIZE - 1 || initialDelayMillis > (maxDelayMillis >> retryAttempt)) { + // initialDelayMillis * 2^retryAttempt would exceed maxDelayMillis (or overflow) + cappedDelay = maxDelayMillis; + } else { + cappedDelay = Math.min(initialDelayMillis << retryAttempt, maxDelayMillis); // 2^retryAttempt + } + return Duration.ofMillis(addSymmetricJitter(cappedDelay)); + } + + /** + * Attempts to parse a string as a long, returning empty Optional on failure. + */ + private Optional tryParseLong(String value) { + if (value == null) { + return Optional.empty(); + } + try { + return Optional.of(Long.parseLong(value)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + /** + * Attempts to parse a string as an HTTP date (RFC 1123), returning empty Optional on failure. + */ + private Optional tryParseHttpDate(String value) { + if (value == null) { + return Optional.empty(); + } + try { + return Optional.of(ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME)); + } catch (DateTimeParseException e) { + return Optional.empty(); + } + } + + /** + * Adds positive jitter (100-120% of original value) to prevent thundering herd. + * Used for X-RateLimit-Reset header delays. + */ + private long addPositiveJitter(long delayMs) { + double jitterMultiplier = 1.0 + (random.nextDouble() * jitterFactor); + return (long) (delayMs * jitterMultiplier); + } + + /** + * Adds symmetric jitter (90-110% of original value) to prevent thundering herd. + * Used for exponential backoff delays. + */ + private long addSymmetricJitter(long delayMs) { + double jitterMultiplier = 1.0 + ((random.nextDouble() - 0.5) * jitterFactor); + return (long) (delayMs * jitterMultiplier); + } + private static boolean shouldRetry(int statusCode) { return statusCode == 408 || statusCode == 429 || statusCode >= 500; } + /** + * Per-request override carried on the OkHttp {@link Request} as a tag. + * When present, the interceptor uses this value instead of the client-wide + * {@code maxRetries} configured at construction time. + */ + public static final class MaxRetriesOverride { + private final int value; + + public MaxRetriesOverride(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + private final class ExponentialBackoff { private final int maxNumRetries; @@ -66,14 +229,14 @@ private final class ExponentialBackoff { this.maxNumRetries = maxNumRetries; } - public Optional nextBackoff() { - retryNumber += 1; - if (retryNumber > maxNumRetries) { + public Optional nextBackoff(Response response) { + if (retryNumber >= maxNumRetries) { return Optional.empty(); } - int upperBound = (int) Math.pow(2, retryNumber); - return Optional.of(ONE_SECOND.multipliedBy(random.nextInt(upperBound))); + Duration delay = getRetryDelayFromHeaders(response, retryNumber); + retryNumber += 1; + return Optional.of(delay); } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/Rfc2822DateTimeDeserializer.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/Rfc2822DateTimeDeserializer.java new file mode 100644 index 00000000..3a826210 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/Rfc2822DateTimeDeserializer.java @@ -0,0 +1,25 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Custom deserializer that handles converting RFC 2822 (RFC 1123) dates into {@link OffsetDateTime} objects. + * This is used for fields with format "date-time-rfc-2822", such as Twilio's dateCreated, dateSent, dateUpdated. + */ +public class Rfc2822DateTimeDeserializer extends JsonDeserializer { + + @Override + public OffsetDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { + String raw = parser.getValueAsString(); + return ZonedDateTime.parse(raw, DateTimeFormatter.RFC_1123_DATE_TIME).toOffsetDateTime(); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/SseEvent.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/SseEvent.java new file mode 100644 index 00000000..9ab823d5 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/SseEvent.java @@ -0,0 +1,114 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; +import java.util.Optional; + +/** + * Represents a Server-Sent Event with all standard fields. + * Used for event-level discrimination where the discriminator is at the SSE envelope level. + * + * @param The type of the data field + */ +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonIgnoreProperties(ignoreUnknown = true) +public final class SseEvent { + private final String event; + private final T data; + private final String id; + private final Long retry; + + private SseEvent(String event, T data, String id, Long retry) { + this.event = event; + this.data = data; + this.id = id; + this.retry = retry; + } + + @JsonProperty("event") + public Optional getEvent() { + return Optional.ofNullable(event); + } + + @JsonProperty("data") + public T getData() { + return data; + } + + @JsonProperty("id") + public Optional getId() { + return Optional.ofNullable(id); + } + + @JsonProperty("retry") + public Optional getRetry() { + return Optional.ofNullable(retry); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SseEvent sseEvent = (SseEvent) o; + return Objects.equals(event, sseEvent.event) + && Objects.equals(data, sseEvent.data) + && Objects.equals(id, sseEvent.id) + && Objects.equals(retry, sseEvent.retry); + } + + @Override + public int hashCode() { + return Objects.hash(event, data, id, retry); + } + + @Override + public String toString() { + return "SseEvent{" + "event='" + + event + '\'' + ", data=" + + data + ", id='" + + id + '\'' + ", retry=" + + retry + '}'; + } + + public static Builder builder() { + return new Builder<>(); + } + + public static final class Builder { + private String event; + private T data; + private String id; + private Long retry; + + private Builder() {} + + public Builder event(String event) { + this.event = event; + return this; + } + + public Builder data(T data) { + this.data = data; + return this; + } + + public Builder id(String id) { + this.id = id; + return this; + } + + public Builder retry(Long retry) { + this.retry = retry; + return this; + } + + public SseEvent build() { + return new SseEvent<>(event, data, id, retry); + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/SseEventParser.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/SseEventParser.java new file mode 100644 index 00000000..ce50f86b --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/SseEventParser.java @@ -0,0 +1,228 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.core.type.TypeReference; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Utility class for parsing Server-Sent Events with support for discriminated unions. + *

+ * Handles two discrimination patterns: + *

    + *
  1. Data-level discrimination: The discriminator (e.g., 'type') is inside the JSON data payload. + * Jackson's polymorphic deserialization handles this automatically.
  2. + *
  3. Event-level discrimination: The discriminator (e.g., 'event') is at the SSE envelope level. + * This requires constructing the full SSE envelope for Jackson to process.
  4. + *
+ */ +public final class SseEventParser { + + private static final Set SSE_ENVELOPE_FIELDS = new HashSet<>(Arrays.asList("event", "data", "id", "retry")); + + private SseEventParser() { + // Utility class + } + + /** + * Parse an SSE event using event-level discrimination. + *

+ * Constructs the full SSE envelope object with event, data, id, and retry fields, + * then deserializes it to the target union type. + * + * @param eventType The SSE event type (from event: field) + * @param data The SSE data content (from data: field) + * @param id The SSE event ID (from id: field), may be null + * @param retry The SSE retry value (from retry: field), may be null + * @param unionClass The target union class + * @param discriminatorProperty The property name used for discrimination (e.g., "event") + * @param The target type + * @return The deserialized object + */ + public static T parseEventLevelUnion( + String eventType, String data, String id, Long retry, Class unionClass, String discriminatorProperty) { + try { + // Determine if data should be parsed as JSON based on the variant's expected type + Object parsedData = parseDataForVariant(eventType, data, unionClass, discriminatorProperty); + + // Construct the SSE envelope object + Map envelope = new HashMap<>(); + envelope.put(discriminatorProperty, eventType); + envelope.put("data", parsedData); + if (id != null) { + envelope.put("id", id); + } + if (retry != null) { + envelope.put("retry", retry); + } + + // Serialize to JSON and deserialize to target type + String envelopeJson = ObjectMappers.JSON_MAPPER.writeValueAsString(envelope); + return ObjectMappers.JSON_MAPPER.readValue(envelopeJson, unionClass); + } catch (Exception e) { + throw new RuntimeException("Failed to parse SSE event with event-level discrimination", e); + } + } + + /** + * Parse an SSE event using data-level discrimination. + *

+ * Simply parses the data field as JSON and deserializes it to the target type. + * Jackson's polymorphic deserialization handles the discrimination automatically. + * + * @param data The SSE data content (from data: field) + * @param valueType The target type + * @param The target type + * @return The deserialized object + */ + public static T parseDataLevelUnion(String data, Class valueType) { + try { + return ObjectMappers.JSON_MAPPER.readValue(data, valueType); + } catch (Exception e) { + throw new RuntimeException("Failed to parse SSE data with data-level discrimination", e); + } + } + + /** + * Determines if the given discriminator property indicates event-level discrimination. + * Event-level discrimination occurs when the discriminator is an SSE envelope field. + * + * @param discriminatorProperty The discriminator property name + * @return true if event-level discrimination, false otherwise + */ + public static boolean isEventLevelDiscrimination(String discriminatorProperty) { + return SSE_ENVELOPE_FIELDS.contains(discriminatorProperty); + } + + /** + * Attempts to find the discriminator property from the union class's Jackson annotations. + * + * @param unionClass The union class to inspect + * @return The discriminator property name, or empty if not found + */ + public static Optional findDiscriminatorProperty(Class unionClass) { + try { + // Look for JsonTypeInfo on the class itself + JsonTypeInfo typeInfo = unionClass.getAnnotation(JsonTypeInfo.class); + if (typeInfo != null && !typeInfo.property().isEmpty()) { + return Optional.of(typeInfo.property()); + } + + // Look for inner Value interface with JsonTypeInfo + for (Class innerClass : unionClass.getDeclaredClasses()) { + typeInfo = innerClass.getAnnotation(JsonTypeInfo.class); + if (typeInfo != null && !typeInfo.property().isEmpty()) { + return Optional.of(typeInfo.property()); + } + } + } catch (Exception e) { + // Ignore reflection errors + } + return Optional.empty(); + } + + /** + * Parse the data field based on what the matching variant expects. + * If the variant expects a String for its data field, returns the raw string. + * Otherwise, parses the data as JSON. + */ + private static Object parseDataForVariant( + String eventType, String data, Class unionClass, String discriminatorProperty) { + if (data == null || data.isEmpty()) { + return data; + } + + try { + // Try to find the variant class that matches this event type + Class variantClass = findVariantClass(unionClass, eventType, discriminatorProperty); + if (variantClass != null) { + // Check if the variant expects a String for the data field + Field dataField = findField(variantClass, "data"); + if (dataField != null && String.class.equals(dataField.getType())) { + // Variant expects String - return raw data + return data; + } + } + + // Try to parse as JSON + return ObjectMappers.JSON_MAPPER.readValue(data, new TypeReference>() {}); + } catch (Exception e) { + // If JSON parsing fails, return as string + return data; + } + } + + /** + * Find the variant class that matches the given discriminator value. + */ + private static Class findVariantClass( + Class unionClass, String discriminatorValue, String discriminatorProperty) { + try { + // Look for JsonSubTypes annotation + JsonSubTypes subTypes = findJsonSubTypes(unionClass); + if (subTypes == null) { + return null; + } + + for (JsonSubTypes.Type subType : subTypes.value()) { + JsonTypeName typeName = subType.value().getAnnotation(JsonTypeName.class); + if (typeName != null && typeName.value().equals(discriminatorValue)) { + return subType.value(); + } + // Also check the name attribute of @JsonSubTypes.Type + if (subType.name().equals(discriminatorValue)) { + return subType.value(); + } + } + } catch (Exception e) { + // Ignore reflection errors + } + return null; + } + + /** + * Find JsonSubTypes annotation on the class or its inner classes. + */ + private static JsonSubTypes findJsonSubTypes(Class unionClass) { + // Check the class itself + JsonSubTypes subTypes = unionClass.getAnnotation(JsonSubTypes.class); + if (subTypes != null) { + return subTypes; + } + + // Check inner classes (for Fern-style unions with inner Value interface) + for (Class innerClass : unionClass.getDeclaredClasses()) { + subTypes = innerClass.getAnnotation(JsonSubTypes.class); + if (subTypes != null) { + return subTypes; + } + } + return null; + } + + /** + * Find a field by name in a class, including private fields. + */ + private static Field findField(Class clazz, String fieldName) { + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + // Check superclass + Class superClass = clazz.getSuperclass(); + if (superClass != null && superClass != Object.class) { + return findField(superClass, fieldName); + } + return null; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/Stream.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/Stream.java index f037712a..3822aa81 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/core/Stream.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/Stream.java @@ -3,6 +3,8 @@ */ package com.skyflow.generated.rest.core; +import java.io.Closeable; +import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.NoSuchElementException; @@ -14,18 +16,30 @@ *

* {@code Stream} assumes that data is being pushed to the provided {@link Reader} asynchronously and utilizes a * {@code Scanner} to block during iteration if the next object is not available. + * Iterable stream for parsing JSON and Server-Sent Events (SSE) data. + * Supports both newline-delimited JSON and SSE with optional stream termination. * * @param The type of objects in the stream. */ -public final class Stream implements Iterable { - /** - * The {@link Class} of the objects in the stream. - */ +public final class Stream implements Iterable, Closeable { + + private static final String NEWLINE = "\n"; + private static final String DATA_PREFIX = "data:"; + + public enum StreamType { + JSON, + SSE, + SSE_EVENT_DISCRIMINATED + } + private final Class valueType; - /** - * The {@link Scanner} used for reading from the input stream and blocking when needed during iteration. - */ private final Scanner scanner; + private final StreamType streamType; + private final String messageTerminator; + private final String streamTerminator; + private final Reader sseReader; + private final String discriminatorProperty; + private boolean isClosed = false; /** * Constructs a new {@code Stream} with the specified value type, reader, and delimiter. @@ -35,8 +49,100 @@ public final class Stream implements Iterable { * @param delimiter The delimiter used to separate elements in the stream. */ public Stream(Class valueType, Reader reader, String delimiter) { + this.valueType = valueType; this.scanner = new Scanner(reader).useDelimiter(delimiter); + this.streamType = StreamType.JSON; + this.messageTerminator = delimiter; + this.streamTerminator = null; + this.sseReader = null; + this.discriminatorProperty = null; + } + + private Stream(Class valueType, StreamType type, Reader reader, String terminator) { + this(valueType, type, reader, terminator, null); + } + + private Stream( + Class valueType, StreamType type, Reader reader, String terminator, String discriminatorProperty) { this.valueType = valueType; + this.streamType = type; + this.discriminatorProperty = discriminatorProperty; + if (type == StreamType.JSON) { + this.scanner = new Scanner(reader).useDelimiter(terminator); + this.messageTerminator = terminator; + this.streamTerminator = null; + this.sseReader = null; + } else { + this.scanner = null; + this.messageTerminator = NEWLINE; + this.streamTerminator = terminator; + this.sseReader = reader; + } + } + + public static Stream fromJson(Class valueType, Reader reader, String delimiter) { + return new Stream<>(valueType, reader, delimiter); + } + + public static Stream fromJson(Class valueType, Reader reader) { + return new Stream<>(valueType, reader, NEWLINE); + } + + public static Stream fromSse(Class valueType, Reader sseReader) { + return new Stream<>(valueType, StreamType.SSE, sseReader, null); + } + + public static Stream fromSse(Class valueType, Reader sseReader, String streamTerminator) { + return new Stream<>(valueType, StreamType.SSE, sseReader, streamTerminator); + } + + /** + * Creates a stream from SSE data with event-level discrimination support. + * Use this when the SSE payload is a discriminated union where the discriminator + * is an SSE envelope field (e.g., 'event'). + * + * @param valueType The class of the objects in the stream. + * @param sseReader The reader that provides the SSE data. + * @param discriminatorProperty The property name used for discrimination (e.g., "event"). + * @param The type of objects in the stream. + * @return A new Stream instance configured for SSE with event-level discrimination. + */ + public static Stream fromSseWithEventDiscrimination( + Class valueType, Reader sseReader, String discriminatorProperty) { + return new Stream<>(valueType, StreamType.SSE_EVENT_DISCRIMINATED, sseReader, null, discriminatorProperty); + } + + /** + * Creates a stream from SSE data with event-level discrimination support and a stream terminator. + * + * @param valueType The class of the objects in the stream. + * @param sseReader The reader that provides the SSE data. + * @param discriminatorProperty The property name used for discrimination (e.g., "event"). + * @param streamTerminator The terminator string that signals end of stream (e.g., "[DONE]"). + * @param The type of objects in the stream. + * @return A new Stream instance configured for SSE with event-level discrimination. + */ + public static Stream fromSseWithEventDiscrimination( + Class valueType, Reader sseReader, String discriminatorProperty, String streamTerminator) { + return new Stream<>( + valueType, StreamType.SSE_EVENT_DISCRIMINATED, sseReader, streamTerminator, discriminatorProperty); + } + + @Override + public void close() throws IOException { + if (!isClosed) { + isClosed = true; + if (scanner != null) { + scanner.close(); + } + if (sseReader != null) { + sseReader.close(); + } + } + } + + private boolean isStreamClosed() { + return isClosed; } /** @@ -47,51 +153,361 @@ public Stream(Class valueType, Reader reader, String delimiter) { */ @Override public Iterator iterator() { - return new Iterator() { - /** - * Returns {@code true} if there are more elements in the stream. - *

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

- * Will block and wait for input if the stream has not ended and the next object is not yet available. - * - * @return The next element in the stream. - * @throws NoSuchElementException If there are no more elements in the stream. - */ - @Override - public T next() { - if (!scanner.hasNext()) { - throw new NoSuchElementException(); - } else { + switch (streamType) { + case SSE: + return new SSEIterator(); + case SSE_EVENT_DISCRIMINATED: + return new SSEEventDiscriminatedIterator(); + case JSON: + default: + return new JsonIterator(); + } + } + + private final class JsonIterator implements Iterator { + + /** + * Returns {@code true} if there are more elements in the stream. + *

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

+ * Will block and wait for input if the stream has not ended and the next object is not yet available. + * + * @return The next element in the stream. + * @throws NoSuchElementException If there are no more elements in the stream. + */ + @Override + public T next() { + if (isStreamClosed()) { + throw new NoSuchElementException("Stream is closed"); + } + + if (!scanner.hasNext()) { + throw new NoSuchElementException(); + } else { + try { + T parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(scanner.next().trim(), valueType); + return parsedResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + } + + private final class SSEIterator implements Iterator { + private Scanner sseScanner; + private T nextItem; + private boolean hasNextItem = false; + private boolean endOfStream = false; + private StringBuilder eventDataBuffer = new StringBuilder(); + private String currentEventType = null; + + private SSEIterator() { + if (sseReader != null && !isStreamClosed()) { + this.sseScanner = new Scanner(sseReader); + } else { + this.endOfStream = true; + } + } + + @Override + public boolean hasNext() { + if (isStreamClosed() || endOfStream) { + return false; + } + + if (hasNextItem) { + return true; + } + + return readNextMessage(); + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException("No more elements in stream"); + } + + T result = nextItem; + nextItem = null; + hasNextItem = false; + return result; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + private boolean readNextMessage() { + if (sseScanner == null || isStreamClosed()) { + endOfStream = true; + return false; + } + + try { + while (sseScanner.hasNextLine()) { + String line = sseScanner.nextLine(); + + if (line.trim().isEmpty()) { + if (eventDataBuffer.length() > 0) { + try { + nextItem = ObjectMappers.JSON_MAPPER.readValue(eventDataBuffer.toString(), valueType); + hasNextItem = true; + eventDataBuffer.setLength(0); + currentEventType = null; + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse SSE event: " + parseEx.getMessage()); + eventDataBuffer.setLength(0); + currentEventType = null; + continue; + } + } + continue; + } + + if (line.startsWith(DATA_PREFIX)) { + String dataContent = line.substring(DATA_PREFIX.length()); + if (dataContent.startsWith(" ")) { + dataContent = dataContent.substring(1); + } + + if (eventDataBuffer.length() == 0 + && streamTerminator != null + && dataContent.trim().equals(streamTerminator)) { + endOfStream = true; + return false; + } + + if (eventDataBuffer.length() > 0) { + eventDataBuffer.append('\n'); + } + eventDataBuffer.append(dataContent); + } else if (line.startsWith("event:")) { + String eventValue = line.length() > 6 ? line.substring(6) : ""; + if (eventValue.startsWith(" ")) { + eventValue = eventValue.substring(1); + } + currentEventType = eventValue; + } else if (line.startsWith("id:")) { + // Event ID field (ignored) + } else if (line.startsWith("retry:")) { + // Retry field (ignored) + } else if (line.startsWith(":")) { + // Comment line (ignored) + } + } + + if (eventDataBuffer.length() > 0) { try { - T parsedResponse = ObjectMappers.JSON_MAPPER.readValue( - scanner.next().trim(), valueType); - return parsedResponse; - } catch (Exception e) { - throw new RuntimeException(e); + nextItem = ObjectMappers.JSON_MAPPER.readValue(eventDataBuffer.toString(), valueType); + hasNextItem = true; + eventDataBuffer.setLength(0); + currentEventType = null; + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse final SSE event: " + parseEx.getMessage()); + eventDataBuffer.setLength(0); + currentEventType = null; } } + + endOfStream = true; + return false; + + } catch (Exception e) { + System.err.println("Failed to parse SSE stream: " + e.getMessage()); + endOfStream = true; + return false; + } + } + } + + /** + * Iterator for SSE streams with event-level discrimination. + * Uses SseEventParser to construct the full SSE envelope for Jackson deserialization. + */ + private final class SSEEventDiscriminatedIterator implements Iterator { + private Scanner sseScanner; + private T nextItem; + private boolean hasNextItem = false; + private boolean endOfStream = false; + private StringBuilder eventDataBuffer = new StringBuilder(); + private String currentEventType = null; + private String currentEventId = null; + private Long currentRetry = null; + + private SSEEventDiscriminatedIterator() { + if (sseReader != null && !isStreamClosed()) { + this.sseScanner = new Scanner(sseReader); + } else { + this.endOfStream = true; + } + } + + @Override + public boolean hasNext() { + if (isStreamClosed() || endOfStream) { + return false; } - /** - * Removing elements from {@code Stream} is not supported. - * - * @throws UnsupportedOperationException Always, as removal is not supported. - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); + if (hasNextItem) { + return true; + } + + return readNextMessage(); + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException("No more elements in stream"); + } + + T result = nextItem; + nextItem = null; + hasNextItem = false; + return result; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + private boolean readNextMessage() { + if (sseScanner == null || isStreamClosed()) { + endOfStream = true; + return false; + } + + try { + while (sseScanner.hasNextLine()) { + String line = sseScanner.nextLine(); + + if (line.trim().isEmpty()) { + if (eventDataBuffer.length() > 0 || currentEventType != null) { + try { + // Use SseEventParser for event-level discrimination + nextItem = SseEventParser.parseEventLevelUnion( + currentEventType, + eventDataBuffer.toString(), + currentEventId, + currentRetry, + valueType, + discriminatorProperty); + hasNextItem = true; + resetEventState(); + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse SSE event: " + parseEx.getMessage()); + resetEventState(); + continue; + } + } + continue; + } + + if (line.startsWith(DATA_PREFIX)) { + String dataContent = line.substring(DATA_PREFIX.length()); + if (dataContent.startsWith(" ")) { + dataContent = dataContent.substring(1); + } + + if (eventDataBuffer.length() == 0 + && streamTerminator != null + && dataContent.trim().equals(streamTerminator)) { + endOfStream = true; + return false; + } + + if (eventDataBuffer.length() > 0) { + eventDataBuffer.append('\n'); + } + eventDataBuffer.append(dataContent); + } else if (line.startsWith("event:")) { + String eventValue = line.length() > 6 ? line.substring(6) : ""; + if (eventValue.startsWith(" ")) { + eventValue = eventValue.substring(1); + } + currentEventType = eventValue; + } else if (line.startsWith("id:")) { + String idValue = line.length() > 3 ? line.substring(3) : ""; + if (idValue.startsWith(" ")) { + idValue = idValue.substring(1); + } + currentEventId = idValue; + } else if (line.startsWith("retry:")) { + String retryValue = line.length() > 6 ? line.substring(6) : ""; + if (retryValue.startsWith(" ")) { + retryValue = retryValue.substring(1); + } + try { + currentRetry = Long.parseLong(retryValue.trim()); + } catch (NumberFormatException e) { + // Ignore invalid retry values + } + } else if (line.startsWith(":")) { + // Comment line (ignored) + } + } + + // Handle any remaining buffered data at end of stream + if (eventDataBuffer.length() > 0 || currentEventType != null) { + try { + nextItem = SseEventParser.parseEventLevelUnion( + currentEventType, + eventDataBuffer.toString(), + currentEventId, + currentRetry, + valueType, + discriminatorProperty); + hasNextItem = true; + resetEventState(); + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse final SSE event: " + parseEx.getMessage()); + resetEventState(); + } + } + + endOfStream = true; + return false; + + } catch (Exception e) { + System.err.println("Failed to parse SSE stream: " + e.getMessage()); + endOfStream = true; + return false; } - }; + } + + private void resetEventState() { + eventDataBuffer.setLength(0); + currentEventType = null; + currentEventId = null; + currentRetry = null; + } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/core/WrappedAlias.java b/skyvault/src/main/java/com/skyflow/generated/rest/core/WrappedAlias.java new file mode 100644 index 00000000..352c364e --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/core/WrappedAlias.java @@ -0,0 +1,8 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +public interface WrappedAlias { + Object get(); +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java b/skyvault/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java index 80ae5e7c..9f8ce586 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java @@ -4,20 +4,21 @@ package com.skyflow.generated.rest.errors; import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.types.ErrorResponse; import okhttp3.Response; public final class BadRequestError extends ApiClientApiException { /** * The body of the response that triggered the exception. */ - private final Object body; + private final ErrorResponse body; - public BadRequestError(Object body) { + public BadRequestError(ErrorResponse body) { super("BadRequestError", 400, body); this.body = body; } - public BadRequestError(Object body, Response rawResponse) { + public BadRequestError(ErrorResponse body, Response rawResponse) { super("BadRequestError", 400, body, rawResponse); this.body = body; } @@ -25,8 +26,8 @@ public BadRequestError(Object body, Response rawResponse) { /** * @return the body */ - @Override - public Object body() { + @java.lang.Override + public ErrorResponse body() { return this.body; } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/errors/ForbiddenError.java b/skyvault/src/main/java/com/skyflow/generated/rest/errors/ForbiddenError.java new file mode 100644 index 00000000..f8eb18ff --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/errors/ForbiddenError.java @@ -0,0 +1,33 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.types.ErrorResponse; +import okhttp3.Response; + +public final class ForbiddenError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final ErrorResponse body; + + public ForbiddenError(ErrorResponse body) { + super("ForbiddenError", 403, body); + this.body = body; + } + + public ForbiddenError(ErrorResponse body, Response rawResponse) { + super("ForbiddenError", 403, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public ErrorResponse body() { + return this.body; + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java b/skyvault/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java index ffeed9d7..d29f2b82 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java @@ -26,7 +26,7 @@ public InternalServerError(ErrorResponse body, Response rawResponse) { /** * @return the body */ - @Override + @java.lang.Override public ErrorResponse body() { return this.body; } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java b/skyvault/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java index 1d0a6ad0..f0cdf5b0 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java @@ -4,20 +4,21 @@ package com.skyflow.generated.rest.errors; import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.types.ErrorResponse; import okhttp3.Response; public final class NotFoundError extends ApiClientApiException { /** * The body of the response that triggered the exception. */ - private final Object body; + private final ErrorResponse body; - public NotFoundError(Object body) { + public NotFoundError(ErrorResponse body) { super("NotFoundError", 404, body); this.body = body; } - public NotFoundError(Object body, Response rawResponse) { + public NotFoundError(ErrorResponse body, Response rawResponse) { super("NotFoundError", 404, body, rawResponse); this.body = body; } @@ -25,8 +26,8 @@ public NotFoundError(Object body, Response rawResponse) { /** * @return the body */ - @Override - public Object body() { + @java.lang.Override + public ErrorResponse body() { return this.body; } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/errors/TooManyRequestsError.java b/skyvault/src/main/java/com/skyflow/generated/rest/errors/TooManyRequestsError.java new file mode 100644 index 00000000..e49ef7ef --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/errors/TooManyRequestsError.java @@ -0,0 +1,33 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.types.ErrorResponse; +import okhttp3.Response; + +public final class TooManyRequestsError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final ErrorResponse body; + + public TooManyRequestsError(ErrorResponse body) { + super("TooManyRequestsError", 429, body); + this.body = body; + } + + public TooManyRequestsError(ErrorResponse body, Response rawResponse) { + super("TooManyRequestsError", 429, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public ErrorResponse body() { + return this.body; + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java b/skyvault/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java index 3bc254bc..1035b7f0 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java @@ -4,20 +4,21 @@ package com.skyflow.generated.rest.errors; import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.types.ErrorResponse; import okhttp3.Response; public final class UnauthorizedError extends ApiClientApiException { /** * The body of the response that triggered the exception. */ - private final Object body; + private final ErrorResponse body; - public UnauthorizedError(Object body) { + public UnauthorizedError(ErrorResponse body) { super("UnauthorizedError", 401, body); this.body = body; } - public UnauthorizedError(Object body, Response rawResponse) { + public UnauthorizedError(ErrorResponse body, Response rawResponse) { super("UnauthorizedError", 401, body, rawResponse); this.body = body; } @@ -25,8 +26,8 @@ public UnauthorizedError(Object body, Response rawResponse) { /** * @return the body */ - @Override - public Object body() { + @java.lang.Override + public ErrorResponse body() { return this.body; } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/requests/PatchV2VaultsIdRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/requests/PatchV2VaultsIdRequest.java new file mode 100644 index 00000000..083579b6 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/requests/PatchV2VaultsIdRequest.java @@ -0,0 +1,69 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = PatchV2VaultsIdRequest.Builder.class) +public final class PatchV2VaultsIdRequest { + private final Map additionalProperties; + + private PatchV2VaultsIdRequest(Map additionalProperties) { + this.additionalProperties = additionalProperties; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof PatchV2VaultsIdRequest; + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(PatchV2VaultsIdRequest other) { + return this; + } + + public PatchV2VaultsIdRequest build() { + return new PatchV2VaultsIdRequest(additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java deleted file mode 100644 index 7e2719f2..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; -import com.skyflow.generated.rest.types.V1AuditResponse; - -import java.util.concurrent.CompletableFuture; - -public class AsyncAuditClient { - protected final ClientOptions clientOptions; - - private final AsyncRawAuditClient rawClient; - - public AsyncAuditClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawAuditClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawAuditClient withRawResponse() { - return this.rawClient; - } - - /** - * Lists audit events that match query parameters. - */ - public CompletableFuture auditServiceListAuditEvents(AuditServiceListAuditEventsRequest request) { - return this.rawClient.auditServiceListAuditEvents(request).thenApply(response -> response.body()); - } - - /** - * Lists audit events that match query parameters. - */ - public CompletableFuture auditServiceListAuditEvents( - AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { - return this.rawClient - .auditServiceListAuditEvents(request, requestOptions) - .thenApply(response -> response.body()); - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java deleted file mode 100644 index e1516eaf..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java +++ /dev/null @@ -1,284 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; -import com.skyflow.generated.rest.types.V1AuditResponse; -import okhttp3.*; -import org.jetbrains.annotations.NotNull; - -import java.io.IOException; -import java.util.concurrent.CompletableFuture; - -public class AsyncRawAuditClient { - protected final ClientOptions clientOptions; - - public AsyncRawAuditClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Lists audit events that match query parameters. - */ - public CompletableFuture> auditServiceListAuditEvents( - AuditServiceListAuditEventsRequest request) { - return auditServiceListAuditEvents(request, null); - } - - /** - * Lists audit events that match query parameters. - */ - public CompletableFuture> auditServiceListAuditEvents( - AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/audit/events"); - if (request.getFilterOpsContextChangeId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.changeID", - request.getFilterOpsContextChangeId().get(), - false); - } - if (request.getFilterOpsContextRequestId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.requestID", - request.getFilterOpsContextRequestId().get(), - false); - } - if (request.getFilterOpsContextTraceId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.traceID", - request.getFilterOpsContextTraceId().get(), - false); - } - if (request.getFilterOpsContextSessionId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.sessionID", - request.getFilterOpsContextSessionId().get(), - false); - } - if (request.getFilterOpsContextActor().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.actor", - request.getFilterOpsContextActor().get(), - false); - } - if (request.getFilterOpsContextActorType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.actorType", - request.getFilterOpsContextActorType().get(), - false); - } - if (request.getFilterOpsContextAccessType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.accessType", - request.getFilterOpsContextAccessType().get(), - false); - } - if (request.getFilterOpsContextIpAddress().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.ipAddress", - request.getFilterOpsContextIpAddress().get(), - false); - } - if (request.getFilterOpsContextOrigin().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.origin", - request.getFilterOpsContextOrigin().get(), - false); - } - if (request.getFilterOpsContextAuthMode().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.authMode", - request.getFilterOpsContextAuthMode().get(), - false); - } - if (request.getFilterOpsContextJwtId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.jwtID", - request.getFilterOpsContextJwtId().get(), - false); - } - if (request.getFilterOpsContextBearerTokenContextId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.bearerTokenContextID", - request.getFilterOpsContextBearerTokenContextId().get(), - false); - } - if (request.getFilterOpsParentAccountId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.parentAccountID", - request.getFilterOpsParentAccountId().get(), - false); - } - QueryStringMapper.addQueryParameter(httpUrl, "filterOps.accountID", request.getFilterOpsAccountId(), false); - if (request.getFilterOpsWorkspaceId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.workspaceID", - request.getFilterOpsWorkspaceId().get(), - false); - } - if (request.getFilterOpsVaultId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.vaultID", request.getFilterOpsVaultId().get(), false); - } - if (request.getFilterOpsResourceIDs().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.resourceIDs", - request.getFilterOpsResourceIDs().get(), - false); - } - if (request.getFilterOpsActionType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.actionType", - request.getFilterOpsActionType().get(), - false); - } - if (request.getFilterOpsResourceType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.resourceType", - request.getFilterOpsResourceType().get(), - false); - } - if (request.getFilterOpsTags().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.tags", request.getFilterOpsTags().get(), false); - } - if (request.getFilterOpsResponseCode().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.responseCode", - request.getFilterOpsResponseCode().get(), - false); - } - if (request.getFilterOpsStartTime().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.startTime", - request.getFilterOpsStartTime().get(), - false); - } - if (request.getFilterOpsEndTime().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.endTime", request.getFilterOpsEndTime().get(), false); - } - if (request.getFilterOpsApiName().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.apiName", request.getFilterOpsApiName().get(), false); - } - if (request.getFilterOpsResponseMessage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.responseMessage", - request.getFilterOpsResponseMessage().get(), - false); - } - if (request.getFilterOpsHttpMethod().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.httpMethod", - request.getFilterOpsHttpMethod().get(), - false); - } - if (request.getFilterOpsHttpUri().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.httpURI", request.getFilterOpsHttpUri().get(), false); - } - if (request.getSortOpsSortBy().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "sortOps.sortBy", request.getSortOpsSortBy().get(), false); - } - if (request.getSortOpsOrderBy().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "sortOps.orderBy", request.getSortOpsOrderBy().get(), false); - } - if (request.getAfterOpsTimestamp().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "afterOps.timestamp", - request.getAfterOpsTimestamp().get(), - false); - } - if (request.getAfterOpsChangeId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "afterOps.changeID", request.getAfterOpsChangeId().get(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "limit", request.getLimit().get(), false); - } - if (request.getOffset().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "offset", request.getOffset().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1AuditResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java deleted file mode 100644 index bac81431..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; -import com.skyflow.generated.rest.types.V1AuditResponse; - -public class AuditClient { - protected final ClientOptions clientOptions; - - private final RawAuditClient rawClient; - - public AuditClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new RawAuditClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawAuditClient withRawResponse() { - return this.rawClient; - } - - /** - * Lists audit events that match query parameters. - */ - public V1AuditResponse auditServiceListAuditEvents(AuditServiceListAuditEventsRequest request) { - return this.rawClient.auditServiceListAuditEvents(request).body(); - } - - /** - * Lists audit events that match query parameters. - */ - public V1AuditResponse auditServiceListAuditEvents( - AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { - return this.rawClient - .auditServiceListAuditEvents(request, requestOptions) - .body(); - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java deleted file mode 100644 index 68cd5e3b..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java +++ /dev/null @@ -1,267 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; -import com.skyflow.generated.rest.types.V1AuditResponse; -import okhttp3.*; - -import java.io.IOException; - -public class RawAuditClient { - protected final ClientOptions clientOptions; - - public RawAuditClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Lists audit events that match query parameters. - */ - public ApiClientHttpResponse auditServiceListAuditEvents( - AuditServiceListAuditEventsRequest request) { - return auditServiceListAuditEvents(request, null); - } - - /** - * Lists audit events that match query parameters. - */ - public ApiClientHttpResponse auditServiceListAuditEvents( - AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/audit/events"); - if (request.getFilterOpsContextChangeId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.changeID", - request.getFilterOpsContextChangeId().get(), - false); - } - if (request.getFilterOpsContextRequestId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.requestID", - request.getFilterOpsContextRequestId().get(), - false); - } - if (request.getFilterOpsContextTraceId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.traceID", - request.getFilterOpsContextTraceId().get(), - false); - } - if (request.getFilterOpsContextSessionId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.sessionID", - request.getFilterOpsContextSessionId().get(), - false); - } - if (request.getFilterOpsContextActor().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.actor", - request.getFilterOpsContextActor().get(), - false); - } - if (request.getFilterOpsContextActorType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.actorType", - request.getFilterOpsContextActorType().get(), - false); - } - if (request.getFilterOpsContextAccessType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.accessType", - request.getFilterOpsContextAccessType().get(), - false); - } - if (request.getFilterOpsContextIpAddress().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.ipAddress", - request.getFilterOpsContextIpAddress().get(), - false); - } - if (request.getFilterOpsContextOrigin().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.origin", - request.getFilterOpsContextOrigin().get(), - false); - } - if (request.getFilterOpsContextAuthMode().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.authMode", - request.getFilterOpsContextAuthMode().get(), - false); - } - if (request.getFilterOpsContextJwtId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.jwtID", - request.getFilterOpsContextJwtId().get(), - false); - } - if (request.getFilterOpsContextBearerTokenContextId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.context.bearerTokenContextID", - request.getFilterOpsContextBearerTokenContextId().get(), - false); - } - if (request.getFilterOpsParentAccountId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.parentAccountID", - request.getFilterOpsParentAccountId().get(), - false); - } - QueryStringMapper.addQueryParameter(httpUrl, "filterOps.accountID", request.getFilterOpsAccountId(), false); - if (request.getFilterOpsWorkspaceId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.workspaceID", - request.getFilterOpsWorkspaceId().get(), - false); - } - if (request.getFilterOpsVaultId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.vaultID", request.getFilterOpsVaultId().get(), false); - } - if (request.getFilterOpsResourceIDs().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.resourceIDs", - request.getFilterOpsResourceIDs().get(), - false); - } - if (request.getFilterOpsActionType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.actionType", - request.getFilterOpsActionType().get(), - false); - } - if (request.getFilterOpsResourceType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.resourceType", - request.getFilterOpsResourceType().get(), - false); - } - if (request.getFilterOpsTags().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.tags", request.getFilterOpsTags().get(), false); - } - if (request.getFilterOpsResponseCode().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.responseCode", - request.getFilterOpsResponseCode().get(), - false); - } - if (request.getFilterOpsStartTime().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.startTime", - request.getFilterOpsStartTime().get(), - false); - } - if (request.getFilterOpsEndTime().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.endTime", request.getFilterOpsEndTime().get(), false); - } - if (request.getFilterOpsApiName().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.apiName", request.getFilterOpsApiName().get(), false); - } - if (request.getFilterOpsResponseMessage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.responseMessage", - request.getFilterOpsResponseMessage().get(), - false); - } - if (request.getFilterOpsHttpMethod().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "filterOps.httpMethod", - request.getFilterOpsHttpMethod().get(), - false); - } - if (request.getFilterOpsHttpUri().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "filterOps.httpURI", request.getFilterOpsHttpUri().get(), false); - } - if (request.getSortOpsSortBy().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "sortOps.sortBy", request.getSortOpsSortBy().get(), false); - } - if (request.getSortOpsOrderBy().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "sortOps.orderBy", request.getSortOpsOrderBy().get(), false); - } - if (request.getAfterOpsTimestamp().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "afterOps.timestamp", - request.getAfterOpsTimestamp().get(), - false); - } - if (request.getAfterOpsChangeId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "afterOps.changeID", request.getAfterOpsChangeId().get(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "limit", request.getLimit().get(), false); - } - if (request.getOffset().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "offset", request.getOffset().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1AuditResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java deleted file mode 100644 index e9f8cf12..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java +++ /dev/null @@ -1,1579 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.audit.types.*; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = AuditServiceListAuditEventsRequest.Builder.class) -public final class AuditServiceListAuditEventsRequest { - private final Optional filterOpsContextChangeId; - - private final Optional filterOpsContextRequestId; - - private final Optional filterOpsContextTraceId; - - private final Optional filterOpsContextSessionId; - - private final Optional filterOpsContextActor; - - private final Optional filterOpsContextActorType; - - private final Optional filterOpsContextAccessType; - - private final Optional filterOpsContextIpAddress; - - private final Optional filterOpsContextOrigin; - - private final Optional filterOpsContextAuthMode; - - private final Optional filterOpsContextJwtId; - - private final Optional filterOpsContextBearerTokenContextId; - - private final Optional filterOpsParentAccountId; - - private final String filterOpsAccountId; - - private final Optional filterOpsWorkspaceId; - - private final Optional filterOpsVaultId; - - private final Optional filterOpsResourceIDs; - - private final Optional filterOpsActionType; - - private final Optional filterOpsResourceType; - - private final Optional filterOpsTags; - - private final Optional filterOpsResponseCode; - - private final Optional filterOpsStartTime; - - private final Optional filterOpsEndTime; - - private final Optional filterOpsApiName; - - private final Optional filterOpsResponseMessage; - - private final Optional filterOpsHttpMethod; - - private final Optional filterOpsHttpUri; - - private final Optional sortOpsSortBy; - - private final Optional sortOpsOrderBy; - - private final Optional afterOpsTimestamp; - - private final Optional afterOpsChangeId; - - private final Optional limit; - - private final Optional offset; - - private final Map additionalProperties; - - private AuditServiceListAuditEventsRequest( - Optional filterOpsContextChangeId, - Optional filterOpsContextRequestId, - Optional filterOpsContextTraceId, - Optional filterOpsContextSessionId, - Optional filterOpsContextActor, - Optional filterOpsContextActorType, - Optional filterOpsContextAccessType, - Optional filterOpsContextIpAddress, - Optional filterOpsContextOrigin, - Optional filterOpsContextAuthMode, - Optional filterOpsContextJwtId, - Optional filterOpsContextBearerTokenContextId, - Optional filterOpsParentAccountId, - String filterOpsAccountId, - Optional filterOpsWorkspaceId, - Optional filterOpsVaultId, - Optional filterOpsResourceIDs, - Optional filterOpsActionType, - Optional filterOpsResourceType, - Optional filterOpsTags, - Optional filterOpsResponseCode, - Optional filterOpsStartTime, - Optional filterOpsEndTime, - Optional filterOpsApiName, - Optional filterOpsResponseMessage, - Optional filterOpsHttpMethod, - Optional filterOpsHttpUri, - Optional sortOpsSortBy, - Optional sortOpsOrderBy, - Optional afterOpsTimestamp, - Optional afterOpsChangeId, - Optional limit, - Optional offset, - Map additionalProperties) { - this.filterOpsContextChangeId = filterOpsContextChangeId; - this.filterOpsContextRequestId = filterOpsContextRequestId; - this.filterOpsContextTraceId = filterOpsContextTraceId; - this.filterOpsContextSessionId = filterOpsContextSessionId; - this.filterOpsContextActor = filterOpsContextActor; - this.filterOpsContextActorType = filterOpsContextActorType; - this.filterOpsContextAccessType = filterOpsContextAccessType; - this.filterOpsContextIpAddress = filterOpsContextIpAddress; - this.filterOpsContextOrigin = filterOpsContextOrigin; - this.filterOpsContextAuthMode = filterOpsContextAuthMode; - this.filterOpsContextJwtId = filterOpsContextJwtId; - this.filterOpsContextBearerTokenContextId = filterOpsContextBearerTokenContextId; - this.filterOpsParentAccountId = filterOpsParentAccountId; - this.filterOpsAccountId = filterOpsAccountId; - this.filterOpsWorkspaceId = filterOpsWorkspaceId; - this.filterOpsVaultId = filterOpsVaultId; - this.filterOpsResourceIDs = filterOpsResourceIDs; - this.filterOpsActionType = filterOpsActionType; - this.filterOpsResourceType = filterOpsResourceType; - this.filterOpsTags = filterOpsTags; - this.filterOpsResponseCode = filterOpsResponseCode; - this.filterOpsStartTime = filterOpsStartTime; - this.filterOpsEndTime = filterOpsEndTime; - this.filterOpsApiName = filterOpsApiName; - this.filterOpsResponseMessage = filterOpsResponseMessage; - this.filterOpsHttpMethod = filterOpsHttpMethod; - this.filterOpsHttpUri = filterOpsHttpUri; - this.sortOpsSortBy = sortOpsSortBy; - this.sortOpsOrderBy = sortOpsOrderBy; - this.afterOpsTimestamp = afterOpsTimestamp; - this.afterOpsChangeId = afterOpsChangeId; - this.limit = limit; - this.offset = offset; - this.additionalProperties = additionalProperties; - } - - /** - * @return ID for the audit event. - */ - @JsonProperty("filterOps.context.changeID") - public Optional getFilterOpsContextChangeId() { - return filterOpsContextChangeId; - } - - /** - * @return ID for the request that caused the event. - */ - @JsonProperty("filterOps.context.requestID") - public Optional getFilterOpsContextRequestId() { - return filterOpsContextRequestId; - } - - /** - * @return ID for the request set by the service that received the request. - */ - @JsonProperty("filterOps.context.traceID") - public Optional getFilterOpsContextTraceId() { - return filterOpsContextTraceId; - } - - /** - * @return ID for the session in which the request was sent. - */ - @JsonProperty("filterOps.context.sessionID") - public Optional getFilterOpsContextSessionId() { - return filterOpsContextSessionId; - } - - /** - * @return Member who sent the request. Depending on actorType, this may be a user ID or a service account ID. - */ - @JsonProperty("filterOps.context.actor") - public Optional getFilterOpsContextActor() { - return filterOpsContextActor; - } - - /** - * @return Type of member who sent the request. - */ - @JsonProperty("filterOps.context.actorType") - public Optional getFilterOpsContextActorType() { - return filterOpsContextActorType; - } - - /** - * @return Type of access for the request. - */ - @JsonProperty("filterOps.context.accessType") - public Optional getFilterOpsContextAccessType() { - return filterOpsContextAccessType; - } - - /** - * @return IP Address of the client that made the request. - */ - @JsonProperty("filterOps.context.ipAddress") - public Optional getFilterOpsContextIpAddress() { - return filterOpsContextIpAddress; - } - - /** - * @return HTTP Origin request header (including scheme, hostname, and port) of the request. - */ - @JsonProperty("filterOps.context.origin") - public Optional getFilterOpsContextOrigin() { - return filterOpsContextOrigin; - } - - /** - * @return Authentication mode the actor used. - */ - @JsonProperty("filterOps.context.authMode") - public Optional getFilterOpsContextAuthMode() { - return filterOpsContextAuthMode; - } - - /** - * @return ID of the JWT token. - */ - @JsonProperty("filterOps.context.jwtID") - public Optional getFilterOpsContextJwtId() { - return filterOpsContextJwtId; - } - - /** - * @return Embedded User Context. - */ - @JsonProperty("filterOps.context.bearerTokenContextID") - public Optional getFilterOpsContextBearerTokenContextId() { - return filterOpsContextBearerTokenContextId; - } - - /** - * @return Resources with the specified parent account ID. - */ - @JsonProperty("filterOps.parentAccountID") - public Optional getFilterOpsParentAccountId() { - return filterOpsParentAccountId; - } - - /** - * @return Resources with the specified account ID. - */ - @JsonProperty("filterOps.accountID") - public String getFilterOpsAccountId() { - return filterOpsAccountId; - } - - /** - * @return Resources with the specified workspace ID. - */ - @JsonProperty("filterOps.workspaceID") - public Optional getFilterOpsWorkspaceId() { - return filterOpsWorkspaceId; - } - - /** - * @return Resources with the specified vault ID. - */ - @JsonProperty("filterOps.vaultID") - public Optional getFilterOpsVaultId() { - return filterOpsVaultId; - } - - /** - * @return Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "<resourceType>/<resourceID>". For example, "VAULT/12345, USER/67890". - */ - @JsonProperty("filterOps.resourceIDs") - public Optional getFilterOpsResourceIDs() { - return filterOpsResourceIDs; - } - - /** - * @return Events with the specified action type. - */ - @JsonProperty("filterOps.actionType") - public Optional getFilterOpsActionType() { - return filterOpsActionType; - } - - /** - * @return Resources with the specified type. - */ - @JsonProperty("filterOps.resourceType") - public Optional getFilterOpsResourceType() { - return filterOpsResourceType; - } - - /** - * @return Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get". - */ - @JsonProperty("filterOps.tags") - public Optional getFilterOpsTags() { - return filterOpsTags; - } - - /** - * @return HTTP response code of the request. - */ - @JsonProperty("filterOps.responseCode") - public Optional getFilterOpsResponseCode() { - return filterOpsResponseCode; - } - - /** - * @return Start timestamp for the query, in SQL format. - */ - @JsonProperty("filterOps.startTime") - public Optional getFilterOpsStartTime() { - return filterOpsStartTime; - } - - /** - * @return End timestamp for the query, in SQL format. - */ - @JsonProperty("filterOps.endTime") - public Optional getFilterOpsEndTime() { - return filterOpsEndTime; - } - - /** - * @return Name of the API called in the request. - */ - @JsonProperty("filterOps.apiName") - public Optional getFilterOpsApiName() { - return filterOpsApiName; - } - - /** - * @return Response message of the request. - */ - @JsonProperty("filterOps.responseMessage") - public Optional getFilterOpsResponseMessage() { - return filterOpsResponseMessage; - } - - /** - * @return HTTP method of the request. - */ - @JsonProperty("filterOps.httpMethod") - public Optional getFilterOpsHttpMethod() { - return filterOpsHttpMethod; - } - - /** - * @return HTTP URI of the request. - */ - @JsonProperty("filterOps.httpURI") - public Optional getFilterOpsHttpUri() { - return filterOpsHttpUri; - } - - /** - * @return Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase"). - */ - @JsonProperty("sortOps.sortBy") - public Optional getSortOpsSortBy() { - return sortOpsSortBy; - } - - /** - * @return Ascending or descending ordering of results. - */ - @JsonProperty("sortOps.orderBy") - public Optional getSortOpsOrderBy() { - return sortOpsOrderBy; - } - - /** - * @return Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. - */ - @JsonProperty("afterOps.timestamp") - public Optional getAfterOpsTimestamp() { - return afterOpsTimestamp; - } - - /** - * @return Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. - */ - @JsonProperty("afterOps.changeID") - public Optional getAfterOpsChangeId() { - return afterOpsChangeId; - } - - /** - * @return Number of results to return. - */ - @JsonProperty("limit") - public Optional getLimit() { - return limit; - } - - /** - * @return Record position at which to start returning results. - */ - @JsonProperty("offset") - public Optional getOffset() { - return offset; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof AuditServiceListAuditEventsRequest - && equalTo((AuditServiceListAuditEventsRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(AuditServiceListAuditEventsRequest other) { - return filterOpsContextChangeId.equals(other.filterOpsContextChangeId) - && filterOpsContextRequestId.equals(other.filterOpsContextRequestId) - && filterOpsContextTraceId.equals(other.filterOpsContextTraceId) - && filterOpsContextSessionId.equals(other.filterOpsContextSessionId) - && filterOpsContextActor.equals(other.filterOpsContextActor) - && filterOpsContextActorType.equals(other.filterOpsContextActorType) - && filterOpsContextAccessType.equals(other.filterOpsContextAccessType) - && filterOpsContextIpAddress.equals(other.filterOpsContextIpAddress) - && filterOpsContextOrigin.equals(other.filterOpsContextOrigin) - && filterOpsContextAuthMode.equals(other.filterOpsContextAuthMode) - && filterOpsContextJwtId.equals(other.filterOpsContextJwtId) - && filterOpsContextBearerTokenContextId.equals(other.filterOpsContextBearerTokenContextId) - && filterOpsParentAccountId.equals(other.filterOpsParentAccountId) - && filterOpsAccountId.equals(other.filterOpsAccountId) - && filterOpsWorkspaceId.equals(other.filterOpsWorkspaceId) - && filterOpsVaultId.equals(other.filterOpsVaultId) - && filterOpsResourceIDs.equals(other.filterOpsResourceIDs) - && filterOpsActionType.equals(other.filterOpsActionType) - && filterOpsResourceType.equals(other.filterOpsResourceType) - && filterOpsTags.equals(other.filterOpsTags) - && filterOpsResponseCode.equals(other.filterOpsResponseCode) - && filterOpsStartTime.equals(other.filterOpsStartTime) - && filterOpsEndTime.equals(other.filterOpsEndTime) - && filterOpsApiName.equals(other.filterOpsApiName) - && filterOpsResponseMessage.equals(other.filterOpsResponseMessage) - && filterOpsHttpMethod.equals(other.filterOpsHttpMethod) - && filterOpsHttpUri.equals(other.filterOpsHttpUri) - && sortOpsSortBy.equals(other.sortOpsSortBy) - && sortOpsOrderBy.equals(other.sortOpsOrderBy) - && afterOpsTimestamp.equals(other.afterOpsTimestamp) - && afterOpsChangeId.equals(other.afterOpsChangeId) - && limit.equals(other.limit) - && offset.equals(other.offset); - } - - @Override - public int hashCode() { - return Objects.hash( - this.filterOpsContextChangeId, - this.filterOpsContextRequestId, - this.filterOpsContextTraceId, - this.filterOpsContextSessionId, - this.filterOpsContextActor, - this.filterOpsContextActorType, - this.filterOpsContextAccessType, - this.filterOpsContextIpAddress, - this.filterOpsContextOrigin, - this.filterOpsContextAuthMode, - this.filterOpsContextJwtId, - this.filterOpsContextBearerTokenContextId, - this.filterOpsParentAccountId, - this.filterOpsAccountId, - this.filterOpsWorkspaceId, - this.filterOpsVaultId, - this.filterOpsResourceIDs, - this.filterOpsActionType, - this.filterOpsResourceType, - this.filterOpsTags, - this.filterOpsResponseCode, - this.filterOpsStartTime, - this.filterOpsEndTime, - this.filterOpsApiName, - this.filterOpsResponseMessage, - this.filterOpsHttpMethod, - this.filterOpsHttpUri, - this.sortOpsSortBy, - this.sortOpsOrderBy, - this.afterOpsTimestamp, - this.afterOpsChangeId, - this.limit, - this.offset); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FilterOpsAccountIdStage builder() { - return new Builder(); - } - - public interface FilterOpsAccountIdStage { - /** - * Resources with the specified account ID. - */ - _FinalStage filterOpsAccountId(@NotNull String filterOpsAccountId); - - Builder from(AuditServiceListAuditEventsRequest other); - } - - public interface _FinalStage { - AuditServiceListAuditEventsRequest build(); - - /** - *

ID for the audit event.

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

ID for the request that caused the event.

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

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

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

ID for the session in which the request was sent.

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

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

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

Type of member who sent the request.

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

Type of access for the request.

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

IP Address of the client that made the request.

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

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

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

Authentication mode the actor used.

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

ID of the JWT token.

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

Embedded User Context.

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

Resources with the specified parent account ID.

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

Resources with the specified workspace ID.

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

Resources with the specified vault ID.

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

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

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

Events with the specified action type.

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

Resources with the specified type.

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

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

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

HTTP response code of the request.

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

Start timestamp for the query, in SQL format.

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

End timestamp for the query, in SQL format.

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

Name of the API called in the request.

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

Response message of the request.

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

HTTP method of the request.

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

HTTP URI of the request.

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

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

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

Ascending or descending ordering of results.

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

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

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

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

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

Number of results to return.

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

Record position at which to start returning results.

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

Resources with the specified account ID.

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

Record position at which to start returning results.

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

Record position at which to start returning results.

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

Number of results to return.

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

Number of results to return.

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

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

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

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

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

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

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

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

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

Ascending or descending ordering of results.

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

Ascending or descending ordering of results.

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

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

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

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

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

HTTP URI of the request.

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

HTTP URI of the request.

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

HTTP method of the request.

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

HTTP method of the request.

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

Response message of the request.

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

Response message of the request.

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

Name of the API called in the request.

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

Name of the API called in the request.

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

End timestamp for the query, in SQL format.

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

End timestamp for the query, in SQL format.

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

Start timestamp for the query, in SQL format.

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

Start timestamp for the query, in SQL format.

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

HTTP response code of the request.

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

HTTP response code of the request.

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

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

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

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

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

Resources with the specified type.

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

Resources with the specified type.

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

Events with the specified action type.

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

Events with the specified action type.

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

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

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

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

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

Resources with the specified vault ID.

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

Resources with the specified vault ID.

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

Resources with the specified workspace ID.

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

Resources with the specified workspace ID.

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

Resources with the specified parent account ID.

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

Resources with the specified parent account ID.

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

Embedded User Context.

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

Embedded User Context.

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

ID of the JWT token.

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

ID of the JWT token.

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

Authentication mode the actor used.

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

Authentication mode the actor used.

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

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

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

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

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

IP Address of the client that made the request.

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

IP Address of the client that made the request.

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

Type of access for the request.

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

Type of access for the request.

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

Type of member who sent the request.

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

Type of member who sent the request.

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

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

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

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

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

ID for the session in which the request was sent.

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

ID for the session in which the request was sent.

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

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

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

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

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

ID for the request that caused the event.

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

ID for the request that caused the event.

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

ID for the audit event.

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

ID for the audit event.

- */ - @Override - @JsonSetter(value = "filterOps.context.changeID", nulls = Nulls.SKIP) - public _FinalStage filterOpsContextChangeId(Optional filterOpsContextChangeId) { - this.filterOpsContextChangeId = filterOpsContextChangeId; - return this; - } - - @Override - public AuditServiceListAuditEventsRequest build() { - return new AuditServiceListAuditEventsRequest( - filterOpsContextChangeId, - filterOpsContextRequestId, - filterOpsContextTraceId, - filterOpsContextSessionId, - filterOpsContextActor, - filterOpsContextActorType, - filterOpsContextAccessType, - filterOpsContextIpAddress, - filterOpsContextOrigin, - filterOpsContextAuthMode, - filterOpsContextJwtId, - filterOpsContextBearerTokenContextId, - filterOpsParentAccountId, - filterOpsAccountId, - filterOpsWorkspaceId, - filterOpsVaultId, - filterOpsResourceIDs, - filterOpsActionType, - filterOpsResourceType, - filterOpsTags, - filterOpsResponseCode, - filterOpsStartTime, - filterOpsEndTime, - filterOpsApiName, - filterOpsResponseMessage, - filterOpsHttpMethod, - filterOpsHttpUri, - sortOpsSortBy, - sortOpsOrderBy, - afterOpsTimestamp, - afterOpsChangeId, - limit, - offset, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsActionType.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsActionType.java deleted file mode 100644 index 9611f8ab..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsActionType.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum AuditServiceListAuditEventsRequestFilterOpsActionType { - NONE("NONE"), - - ASSIGN("ASSIGN"), - - CREATE("CREATE"), - - DELETE("DELETE"), - - EXECUTE("EXECUTE"), - - LIST("LIST"), - - READ("READ"), - - UNASSIGN("UNASSIGN"), - - UPDATE("UPDATE"), - - VALIDATE("VALIDATE"), - - LOGIN("LOGIN"), - - ROTATE("ROTATE"), - - SCHEDULEROTATION("SCHEDULEROTATION"), - - SCHEDULEROTATIONALERT("SCHEDULEROTATIONALERT"), - - IMPORT("IMPORT"), - - GETIMPORTPARAMETERS("GETIMPORTPARAMETERS"), - - PING("PING"), - - GETCLOUDPROVIDER("GETCLOUDPROVIDER"); - - private final String value; - - AuditServiceListAuditEventsRequestFilterOpsActionType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAccessType.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAccessType.java deleted file mode 100644 index 44ac80d9..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAccessType.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum AuditServiceListAuditEventsRequestFilterOpsContextAccessType { - ACCESS_NONE("ACCESS_NONE"), - - API("API"), - - SQL("SQL"), - - OKTA_LOGIN("OKTA_LOGIN"); - - private final String value; - - AuditServiceListAuditEventsRequestFilterOpsContextAccessType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextActorType.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextActorType.java deleted file mode 100644 index 1948ea9c..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextActorType.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum AuditServiceListAuditEventsRequestFilterOpsContextActorType { - NONE("NONE"), - - USER("USER"), - - SERVICE_ACCOUNT("SERVICE_ACCOUNT"); - - private final String value; - - AuditServiceListAuditEventsRequestFilterOpsContextActorType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAuthMode.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAuthMode.java deleted file mode 100644 index 82c375aa..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAuthMode.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum AuditServiceListAuditEventsRequestFilterOpsContextAuthMode { - AUTH_NONE("AUTH_NONE"), - - OKTA_JWT("OKTA_JWT"), - - SERVICE_ACCOUNT_JWT("SERVICE_ACCOUNT_JWT"), - - PAT_JWT("PAT_JWT"); - - private final String value; - - AuditServiceListAuditEventsRequestFilterOpsContextAuthMode(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsResourceType.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsResourceType.java deleted file mode 100644 index 864213ec..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsResourceType.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum AuditServiceListAuditEventsRequestFilterOpsResourceType { - NONE_API("NONE_API"), - - ACCOUNT("ACCOUNT"), - - AUDIT("AUDIT"), - - BASE_DATA_TYPE("BASE_DATA_TYPE"), - - FIELD_TEMPLATE("FIELD_TEMPLATE"), - - FILE("FILE"), - - KEY("KEY"), - - POLICY("POLICY"), - - PROTO_PARSE("PROTO_PARSE"), - - RECORD("RECORD"), - - ROLE("ROLE"), - - RULE("RULE"), - - SECRET("SECRET"), - - SERVICE_ACCOUNT("SERVICE_ACCOUNT"), - - TOKEN("TOKEN"), - - USER("USER"), - - VAULT("VAULT"), - - VAULT_TEMPLATE("VAULT_TEMPLATE"), - - WORKSPACE("WORKSPACE"), - - TABLE("TABLE"), - - POLICY_TEMPLATE("POLICY_TEMPLATE"), - - MEMBER("MEMBER"), - - TAG("TAG"), - - CONNECTION("CONNECTION"), - - MIGRATION("MIGRATION"), - - SCHEDULED_JOB("SCHEDULED_JOB"), - - JOB("JOB"), - - COLUMN_NAME("COLUMN_NAME"), - - NETWORK_TOKEN("NETWORK_TOKEN"), - - SUBSCRIPTION("SUBSCRIPTION"); - - private final String value; - - AuditServiceListAuditEventsRequestFilterOpsResourceType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestSortOpsOrderBy.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestSortOpsOrderBy.java deleted file mode 100644 index fe3f928e..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestSortOpsOrderBy.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.audit.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum AuditServiceListAuditEventsRequestSortOpsOrderBy { - ASCENDING("ASCENDING"), - - DESCENDING("DESCENDING"); - - private final String value; - - AuditServiceListAuditEventsRequestSortOpsOrderBy(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncBinLookupClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncBinLookupClient.java deleted file mode 100644 index fb2d07d0..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncBinLookupClient.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.binlookup; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.binlookup.requests.V1BinListRequest; -import com.skyflow.generated.rest.types.V1BinListResponse; - -import java.util.concurrent.CompletableFuture; - -public class AsyncBinLookupClient { - protected final ClientOptions clientOptions; - - private final AsyncRawBinLookupClient rawClient; - - public AsyncBinLookupClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawBinLookupClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawBinLookupClient withRawResponse() { - return this.rawClient; - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public CompletableFuture binListServiceListCardsOfBin() { - return this.rawClient.binListServiceListCardsOfBin().thenApply(response -> response.body()); - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public CompletableFuture binListServiceListCardsOfBin(V1BinListRequest request) { - return this.rawClient.binListServiceListCardsOfBin(request).thenApply(response -> response.body()); - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public CompletableFuture binListServiceListCardsOfBin( - V1BinListRequest request, RequestOptions requestOptions) { - return this.rawClient - .binListServiceListCardsOfBin(request, requestOptions) - .thenApply(response -> response.body()); - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncRawBinLookupClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncRawBinLookupClient.java deleted file mode 100644 index 9cf03c7d..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncRawBinLookupClient.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.binlookup; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.binlookup.requests.V1BinListRequest; -import com.skyflow.generated.rest.types.V1BinListResponse; -import okhttp3.*; -import org.jetbrains.annotations.NotNull; - -import java.io.IOException; -import java.util.concurrent.CompletableFuture; - -public class AsyncRawBinLookupClient { - protected final ClientOptions clientOptions; - - public AsyncRawBinLookupClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public CompletableFuture> binListServiceListCardsOfBin() { - return binListServiceListCardsOfBin(V1BinListRequest.builder().build()); - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public CompletableFuture> binListServiceListCardsOfBin( - V1BinListRequest request) { - return binListServiceListCardsOfBin(request, null); - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public CompletableFuture> binListServiceListCardsOfBin( - V1BinListRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/card_lookup") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BinListResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/BinLookupClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/BinLookupClient.java deleted file mode 100644 index a7822986..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/BinLookupClient.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.binlookup; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.binlookup.requests.V1BinListRequest; -import com.skyflow.generated.rest.types.V1BinListResponse; - -public class BinLookupClient { - protected final ClientOptions clientOptions; - - private final RawBinLookupClient rawClient; - - public BinLookupClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new RawBinLookupClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawBinLookupClient withRawResponse() { - return this.rawClient; - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public V1BinListResponse binListServiceListCardsOfBin() { - return this.rawClient.binListServiceListCardsOfBin().body(); - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public V1BinListResponse binListServiceListCardsOfBin(V1BinListRequest request) { - return this.rawClient.binListServiceListCardsOfBin(request).body(); - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public V1BinListResponse binListServiceListCardsOfBin(V1BinListRequest request, RequestOptions requestOptions) { - return this.rawClient - .binListServiceListCardsOfBin(request, requestOptions) - .body(); - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/RawBinLookupClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/RawBinLookupClient.java deleted file mode 100644 index 21e77017..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/RawBinLookupClient.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.binlookup; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.binlookup.requests.V1BinListRequest; -import com.skyflow.generated.rest.types.V1BinListResponse; -import okhttp3.*; - -import java.io.IOException; - -public class RawBinLookupClient { - protected final ClientOptions clientOptions; - - public RawBinLookupClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public ApiClientHttpResponse binListServiceListCardsOfBin() { - return binListServiceListCardsOfBin(V1BinListRequest.builder().build()); - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public ApiClientHttpResponse binListServiceListCardsOfBin(V1BinListRequest request) { - return binListServiceListCardsOfBin(request, null); - } - - /** - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - */ - public ApiClientHttpResponse binListServiceListCardsOfBin( - V1BinListRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/card_lookup") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BinListResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/requests/V1BinListRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/requests/V1BinListRequest.java deleted file mode 100644 index def40293..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/binlookup/requests/V1BinListRequest.java +++ /dev/null @@ -1,180 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.binlookup.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.types.V1VaultSchemaConfig; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1BinListRequest.Builder.class) -public final class V1BinListRequest { - private final Optional> fields; - - private final Optional bin; - - private final Optional vaultSchemaConfig; - - private final Optional skyflowId; - - private final Map additionalProperties; - - private V1BinListRequest( - Optional> fields, - Optional bin, - Optional vaultSchemaConfig, - Optional skyflowId, - Map additionalProperties) { - this.fields = fields; - this.bin = bin; - this.vaultSchemaConfig = vaultSchemaConfig; - this.skyflowId = skyflowId; - this.additionalProperties = additionalProperties; - } - - /** - * @return Fields to return. If not specified, all fields are returned. - */ - @JsonProperty("fields") - public Optional> getFields() { - return fields; - } - - /** - * @return BIN of the card. - */ - @JsonProperty("BIN") - public Optional getBin() { - return bin; - } - - @JsonProperty("vault_schema_config") - public Optional getVaultSchemaConfig() { - return vaultSchemaConfig; - } - - /** - * @return <code>skyflow_id</code> of the record. - */ - @JsonProperty("skyflow_id") - public Optional getSkyflowId() { - return skyflowId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1BinListRequest && equalTo((V1BinListRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1BinListRequest other) { - return fields.equals(other.fields) - && bin.equals(other.bin) - && vaultSchemaConfig.equals(other.vaultSchemaConfig) - && skyflowId.equals(other.skyflowId); - } - - @Override - public int hashCode() { - return Objects.hash(this.fields, this.bin, this.vaultSchemaConfig, this.skyflowId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional> fields = Optional.empty(); - - private Optional bin = Optional.empty(); - - private Optional vaultSchemaConfig = Optional.empty(); - - private Optional skyflowId = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1BinListRequest other) { - fields(other.getFields()); - bin(other.getBin()); - vaultSchemaConfig(other.getVaultSchemaConfig()); - skyflowId(other.getSkyflowId()); - return this; - } - - /** - *

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

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

BIN of the card.

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

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

- */ - @JsonSetter(value = "skyflow_id", nulls = Nulls.SKIP) - public Builder skyflowId(Optional skyflowId) { - this.skyflowId = skyflowId; - return this; - } - - public Builder skyflowId(String skyflowId) { - this.skyflowId = Optional.ofNullable(skyflowId); - return this; - } - - public V1BinListRequest build() { - return new V1BinListRequest(fields, bin, vaultSchemaConfig, skyflowId, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java index 01031423..80f8236e 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java @@ -5,11 +5,9 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.files.requests.*; -import com.skyflow.generated.rest.types.DeidentifyFileResponse; -import com.skyflow.generated.rest.types.DetectRunsResponse; -import com.skyflow.generated.rest.types.ReidentifyFileResponse; - +import com.skyflow.generated.rest.resources.files.requests.UploadFileRequestV2; +import com.skyflow.generated.rest.types.UploadFileResponseV2; +import java.io.File; import java.util.concurrent.CompletableFuture; public class AsyncFilesClient { @@ -30,181 +28,17 @@ public AsyncRawFilesClient withRawResponse() { } /** - * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). - */ - public CompletableFuture deidentifyFile(DeidentifyFileRequest request) { - return this.rawClient.deidentifyFile(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). - */ - public CompletableFuture deidentifyFile( - DeidentifyFileRequest request, RequestOptions requestOptions) { - return this.rawClient.deidentifyFile(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyAudio( - DeidentifyFileAudioRequestDeidentifyAudio request) { - return this.rawClient.deidentifyAudio(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyAudio( - DeidentifyFileAudioRequestDeidentifyAudio request, RequestOptions requestOptions) { - return this.rawClient.deidentifyAudio(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyDocument( - DeidentifyFileRequestDeidentifyDocument request) { - return this.rawClient.deidentifyDocument(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyDocument( - DeidentifyFileRequestDeidentifyDocument request, RequestOptions requestOptions) { - return this.rawClient.deidentifyDocument(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyPdf( - DeidentifyFileDocumentPdfRequestDeidentifyPdf request) { - return this.rawClient.deidentifyPdf(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyPdf( - DeidentifyFileDocumentPdfRequestDeidentifyPdf request, RequestOptions requestOptions) { - return this.rawClient.deidentifyPdf(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyImage( - DeidentifyFileImageRequestDeidentifyImage request) { - return this.rawClient.deidentifyImage(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyImage( - DeidentifyFileImageRequestDeidentifyImage request, RequestOptions requestOptions) { - return this.rawClient.deidentifyImage(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyPresentation( - DeidentifyFileRequestDeidentifyPresentation request) { - return this.rawClient.deidentifyPresentation(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyPresentation( - DeidentifyFileRequestDeidentifyPresentation request, RequestOptions requestOptions) { - return this.rawClient.deidentifyPresentation(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifySpreadsheet( - DeidentifyFileRequestDeidentifySpreadsheet request) { - return this.rawClient.deidentifySpreadsheet(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifySpreadsheet( - DeidentifyFileRequestDeidentifySpreadsheet request, RequestOptions requestOptions) { - return this.rawClient.deidentifySpreadsheet(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyStructuredText( - DeidentifyFileRequestDeidentifyStructuredText request) { - return this.rawClient.deidentifyStructuredText(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyStructuredText( - DeidentifyFileRequestDeidentifyStructuredText request, RequestOptions requestOptions) { - return this.rawClient.deidentifyStructuredText(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyText(DeidentifyFileRequestDeidentifyText request) { - return this.rawClient.deidentifyText(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture deidentifyText( - DeidentifyFileRequestDeidentifyText request, RequestOptions requestOptions) { - return this.rawClient.deidentifyText(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Re-identifies tokens in a file. - */ - public CompletableFuture reidentifyFile(ReidentifyFileRequestReidentifyFile request) { - return this.rawClient.reidentifyFile(request).thenApply(response -> response.body()); - } - - /** - * Re-identifies tokens in a file. - */ - public CompletableFuture reidentifyFile( - ReidentifyFileRequestReidentifyFile request, RequestOptions requestOptions) { - return this.rawClient.reidentifyFile(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Returns the status of a detect run. - */ - public CompletableFuture getRun(String runId) { - return this.rawClient.getRun(runId).thenApply(response -> response.body()); - } - - /** - * Returns the status of a detect run. + * Uploads a file to a new or specified record. */ - public CompletableFuture getRun(String runId, GetRunRequest request) { - return this.rawClient.getRun(runId, request).thenApply(response -> response.body()); + public CompletableFuture uploadFileV2(String vaultId, File file, UploadFileRequestV2 request) { + return this.rawClient.uploadFileV2(vaultId, file, request).thenApply(response -> response.body()); } /** - * Returns the status of a detect run. + * Uploads a file to a new or specified record. */ - public CompletableFuture getRun( - String runId, GetRunRequest request, RequestOptions requestOptions) { - return this.rawClient.getRun(runId, request, requestOptions).thenApply(response -> response.body()); + public CompletableFuture uploadFileV2( + String vaultId, File file, UploadFileRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.uploadFileV2(vaultId, file, request, requestOptions).thenApply(response -> response.body()); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java index e7f008e8..28ee91e1 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java @@ -4,20 +4,37 @@ package com.skyflow.generated.rest.resources.files; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; import com.skyflow.generated.rest.errors.BadRequestError; import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.NotFoundError; import com.skyflow.generated.rest.errors.UnauthorizedError; -import com.skyflow.generated.rest.resources.files.requests.*; -import com.skyflow.generated.rest.types.DeidentifyFileResponse; -import com.skyflow.generated.rest.types.DetectRunsResponse; +import com.skyflow.generated.rest.resources.files.requests.UploadFileRequestV2; import com.skyflow.generated.rest.types.ErrorResponse; -import com.skyflow.generated.rest.types.ReidentifyFileResponse; -import okhttp3.*; -import org.jetbrains.annotations.NotNull; - +import com.skyflow.generated.rest.types.UploadFileResponseV2; +import java.io.File; import java.io.IOException; +import java.nio.file.Files; import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; public class AsyncRawFilesClient { protected final ClientOptions clientOptions; @@ -27,946 +44,101 @@ public AsyncRawFilesClient(ClientOptions clientOptions) { } /** - * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + * Uploads a file to a new or specified record. */ - public CompletableFuture> deidentifyFile( - DeidentifyFileRequest request) { - return deidentifyFile(request, null); + public CompletableFuture> uploadFileV2( + String vaultId, File file, UploadFileRequestV2 request) { + return uploadFileV2(vaultId, file, request, null); } /** - * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + * Uploads a file to a new or specified record. */ - public CompletableFuture> deidentifyFile( - DeidentifyFileRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> uploadFileV2( + String vaultId, File file, UploadFileRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() - .addPathSegments("v1/detect/deidentify/file") - .build(); - RequestBody body; + .addPathSegments("v2/vaults") + .addPathSegment(vaultId) + .addPathSegments("files") + .addPathSegments("upload"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); + QueryStringMapper.addFormDataPart(multipartBodyBuilder, "tableName", request.getTableName(), false); + QueryStringMapper.addFormDataPart(multipartBodyBuilder, "columnName", request.getColumnName(), false); + if (request.getSkyflowId().isPresent()) { + QueryStringMapper.addFormDataPart( + multipartBodyBuilder, + "skyflowID", + request.getSkyflowId().get(), + false); + } + String fileMimeType = Files.probeContentType(file.toPath()); + MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; + multipartBodyBuilder.addFormDataPart("file", file.getName(), RequestBody.create(file, fileMimeTypeMediaType)); + if (request.getReturnFileMetadata().isPresent()) { + QueryStringMapper.addFormDataPart( + multipartBodyBuilder, + "returnFileMetadata", + request.getReturnFileMetadata().get(), + false); + } + } catch (Exception e) { + throw new RuntimeException(e); } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("POST", multipartBodyBuilder.build()) .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyAudio( - DeidentifyFileAudioRequestDeidentifyAudio request) { - return deidentifyAudio(request, null); - } - - /** - * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyAudio( - DeidentifyFileAudioRequestDeidentifyAudio request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/audio") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); } - CompletableFuture> future = new CompletableFuture<>(); + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), - response)); - return; - } String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyDocument( - DeidentifyFileRequestDeidentifyDocument request) { - return deidentifyDocument(request, null); - } - - /** - * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyDocument( - DeidentifyFileRequestDeidentifyDocument request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/document") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, UploadFileResponseV2.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyPdf( - DeidentifyFileDocumentPdfRequestDeidentifyPdf request) { - return deidentifyPdf(request, null); - } - - /** - * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyPdf( - DeidentifyFileDocumentPdfRequestDeidentifyPdf request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/document/pdf") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; case 401: future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyImage( - DeidentifyFileImageRequestDeidentifyImage request) { - return deidentifyImage(request, null); - } - - /** - * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyImage( - DeidentifyFileImageRequestDeidentifyImage request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/image") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( + case 404: + future.completeExceptionally(new NotFoundError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyPresentation( - DeidentifyFileRequestDeidentifyPresentation request) { - return deidentifyPresentation(request, null); - } - - /** - * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyPresentation( - DeidentifyFileRequestDeidentifyPresentation request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/presentation") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifySpreadsheet( - DeidentifyFileRequestDeidentifySpreadsheet request) { - return deidentifySpreadsheet(request, null); - } - - /** - * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifySpreadsheet( - DeidentifyFileRequestDeidentifySpreadsheet request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/spreadsheet") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyStructuredText( - DeidentifyFileRequestDeidentifyStructuredText request) { - return deidentifyStructuredText(request, null); - } - - /** - * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyStructuredText( - DeidentifyFileRequestDeidentifyStructuredText request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/structured_text") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyText( - DeidentifyFileRequestDeidentifyText request) { - return deidentifyText(request, null); - } - - /** - * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public CompletableFuture> deidentifyText( - DeidentifyFileRequestDeidentifyText request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/text") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeidentifyFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Re-identifies tokens in a file. - */ - public CompletableFuture> reidentifyFile( - ReidentifyFileRequestReidentifyFile request) { - return reidentifyFile(request, null); - } - - /** - * Re-identifies tokens in a file. - */ - public CompletableFuture> reidentifyFile( - ReidentifyFileRequestReidentifyFile request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/reidentify/file") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ReidentifyFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Returns the status of a detect run. - */ - public CompletableFuture> getRun(String runId) { - return getRun(runId, GetRunRequest.builder().build()); - } - - /** - * Returns the status of a detect run. - */ - public CompletableFuture> getRun(String runId, GetRunRequest request) { - return getRun(runId, request, null); - } - - /** - * Returns the status of a detect run. - */ - public CompletableFuture> getRun( - String runId, GetRunRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/runs") - .addPathSegment(runId); - if (request.getVaultId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "vault_id", request.getVaultId().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetectRunsResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; case 500: future.completeExceptionally(new InternalServerError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), @@ -976,12 +148,13 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java index bcda96e6..fec6c802 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java @@ -5,10 +5,9 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.files.requests.*; -import com.skyflow.generated.rest.types.DeidentifyFileResponse; -import com.skyflow.generated.rest.types.DetectRunsResponse; -import com.skyflow.generated.rest.types.ReidentifyFileResponse; +import com.skyflow.generated.rest.resources.files.requests.UploadFileRequestV2; +import com.skyflow.generated.rest.types.UploadFileResponseV2; +import java.io.File; public class FilesClient { protected final ClientOptions clientOptions; @@ -28,172 +27,17 @@ public RawFilesClient withRawResponse() { } /** - * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + * Uploads a file to a new or specified record. */ - public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request) { - return this.rawClient.deidentifyFile(request).body(); + public UploadFileResponseV2 uploadFileV2(String vaultId, File file, UploadFileRequestV2 request) { + return this.rawClient.uploadFileV2(vaultId, file, request).body(); } /** - * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + * Uploads a file to a new or specified record. */ - public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request, RequestOptions requestOptions) { - return this.rawClient.deidentifyFile(request, requestOptions).body(); - } - - /** - * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyAudio(DeidentifyFileAudioRequestDeidentifyAudio request) { - return this.rawClient.deidentifyAudio(request).body(); - } - - /** - * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyAudio( - DeidentifyFileAudioRequestDeidentifyAudio request, RequestOptions requestOptions) { - return this.rawClient.deidentifyAudio(request, requestOptions).body(); - } - - /** - * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyDocument(DeidentifyFileRequestDeidentifyDocument request) { - return this.rawClient.deidentifyDocument(request).body(); - } - - /** - * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyDocument( - DeidentifyFileRequestDeidentifyDocument request, RequestOptions requestOptions) { - return this.rawClient.deidentifyDocument(request, requestOptions).body(); - } - - /** - * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyPdf(DeidentifyFileDocumentPdfRequestDeidentifyPdf request) { - return this.rawClient.deidentifyPdf(request).body(); - } - - /** - * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyPdf( - DeidentifyFileDocumentPdfRequestDeidentifyPdf request, RequestOptions requestOptions) { - return this.rawClient.deidentifyPdf(request, requestOptions).body(); - } - - /** - * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyImage(DeidentifyFileImageRequestDeidentifyImage request) { - return this.rawClient.deidentifyImage(request).body(); - } - - /** - * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyImage( - DeidentifyFileImageRequestDeidentifyImage request, RequestOptions requestOptions) { - return this.rawClient.deidentifyImage(request, requestOptions).body(); - } - - /** - * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyPresentation(DeidentifyFileRequestDeidentifyPresentation request) { - return this.rawClient.deidentifyPresentation(request).body(); - } - - /** - * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyPresentation( - DeidentifyFileRequestDeidentifyPresentation request, RequestOptions requestOptions) { - return this.rawClient.deidentifyPresentation(request, requestOptions).body(); - } - - /** - * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifySpreadsheet(DeidentifyFileRequestDeidentifySpreadsheet request) { - return this.rawClient.deidentifySpreadsheet(request).body(); - } - - /** - * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifySpreadsheet( - DeidentifyFileRequestDeidentifySpreadsheet request, RequestOptions requestOptions) { - return this.rawClient.deidentifySpreadsheet(request, requestOptions).body(); - } - - /** - * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyStructuredText(DeidentifyFileRequestDeidentifyStructuredText request) { - return this.rawClient.deidentifyStructuredText(request).body(); - } - - /** - * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyStructuredText( - DeidentifyFileRequestDeidentifyStructuredText request, RequestOptions requestOptions) { - return this.rawClient.deidentifyStructuredText(request, requestOptions).body(); - } - - /** - * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyText(DeidentifyFileRequestDeidentifyText request) { - return this.rawClient.deidentifyText(request).body(); - } - - /** - * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public DeidentifyFileResponse deidentifyText( - DeidentifyFileRequestDeidentifyText request, RequestOptions requestOptions) { - return this.rawClient.deidentifyText(request, requestOptions).body(); - } - - /** - * Re-identifies tokens in a file. - */ - public ReidentifyFileResponse reidentifyFile(ReidentifyFileRequestReidentifyFile request) { - return this.rawClient.reidentifyFile(request).body(); - } - - /** - * Re-identifies tokens in a file. - */ - public ReidentifyFileResponse reidentifyFile( - ReidentifyFileRequestReidentifyFile request, RequestOptions requestOptions) { - return this.rawClient.reidentifyFile(request, requestOptions).body(); - } - - /** - * Returns the status of a detect run. - */ - public DetectRunsResponse getRun(String runId) { - return this.rawClient.getRun(runId).body(); - } - - /** - * Returns the status of a detect run. - */ - public DetectRunsResponse getRun(String runId, GetRunRequest request) { - return this.rawClient.getRun(runId, request).body(); - } - - /** - * Returns the status of a detect run. - */ - public DetectRunsResponse getRun(String runId, GetRunRequest request, RequestOptions requestOptions) { - return this.rawClient.getRun(runId, request, requestOptions).body(); + public UploadFileResponseV2 uploadFileV2( + String vaultId, File file, UploadFileRequestV2 request, RequestOptions requestOptions) { + return this.rawClient.uploadFileV2(vaultId, file, request, requestOptions).body(); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java index d277d224..3742cf62 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java @@ -4,18 +4,33 @@ package com.skyflow.generated.rest.resources.files; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; import com.skyflow.generated.rest.errors.BadRequestError; import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.NotFoundError; import com.skyflow.generated.rest.errors.UnauthorizedError; -import com.skyflow.generated.rest.resources.files.requests.*; -import com.skyflow.generated.rest.types.DeidentifyFileResponse; -import com.skyflow.generated.rest.types.DetectRunsResponse; +import com.skyflow.generated.rest.resources.files.requests.UploadFileRequestV2; import com.skyflow.generated.rest.types.ErrorResponse; -import com.skyflow.generated.rest.types.ReidentifyFileResponse; -import okhttp3.*; - +import com.skyflow.generated.rest.types.UploadFileResponseV2; +import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class RawFilesClient { protected final ClientOptions clientOptions; @@ -25,395 +40,89 @@ public RawFilesClient(ClientOptions clientOptions) { } /** - * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + * Uploads a file to a new or specified record. */ - public ApiClientHttpResponse deidentifyFile(DeidentifyFileRequest request) { - return deidentifyFile(request, null); + public ApiClientHttpResponse uploadFileV2(String vaultId, File file, UploadFileRequestV2 request) { + return uploadFileV2(vaultId, file, request, null); } /** - * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + * Uploads a file to a new or specified record. */ - public ApiClientHttpResponse deidentifyFile( - DeidentifyFileRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse uploadFileV2( + String vaultId, File file, UploadFileRequestV2 request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() - .addPathSegments("v1/detect/deidentify/file") - .build(); - RequestBody body; + .addPathSegments("v2/vaults") + .addPathSegment(vaultId) + .addPathSegments("files") + .addPathSegments("upload"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } + MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); + QueryStringMapper.addFormDataPart(multipartBodyBuilder, "tableName", request.getTableName(), false); + QueryStringMapper.addFormDataPart(multipartBodyBuilder, "columnName", request.getColumnName(), false); + if (request.getSkyflowId().isPresent()) { + QueryStringMapper.addFormDataPart( + multipartBodyBuilder, + "skyflowID", + request.getSkyflowId().get(), + false); + } + String fileMimeType = Files.probeContentType(file.toPath()); + MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; + multipartBodyBuilder.addFormDataPart("file", file.getName(), RequestBody.create(file, fileMimeTypeMediaType)); + if (request.getReturnFileMetadata().isPresent()) { + QueryStringMapper.addFormDataPart( + multipartBodyBuilder, + "returnFileMetadata", + request.getReturnFileMetadata().get(), + false); + } + } catch (Exception e) { + throw new RuntimeException(e); } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("POST", multipartBodyBuilder.build()) .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyAudio( - DeidentifyFileAudioRequestDeidentifyAudio request) { - return deidentifyAudio(request, null); - } - - /** - * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyAudio( - DeidentifyFileAudioRequestDeidentifyAudio request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/audio") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); - } String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyDocument( - DeidentifyFileRequestDeidentifyDocument request) { - return deidentifyDocument(request, null); - } - - /** - * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyDocument( - DeidentifyFileRequestDeidentifyDocument request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/document") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, UploadFileResponseV2.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyPdf( - DeidentifyFileDocumentPdfRequestDeidentifyPdf request) { - return deidentifyPdf(request, null); - } - - /** - * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyPdf( - DeidentifyFileDocumentPdfRequestDeidentifyPdf request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/document/pdf") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); case 401: throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyImage( - DeidentifyFileImageRequestDeidentifyImage request) { - return deidentifyImage(request, null); - } - - /** - * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyImage( - DeidentifyFileImageRequestDeidentifyImage request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/image") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( + case 404: + throw new NotFoundError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyPresentation( - DeidentifyFileRequestDeidentifyPresentation request) { - return deidentifyPresentation(request, null); - } - - /** - * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyPresentation( - DeidentifyFileRequestDeidentifyPresentation request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/presentation") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); case 500: throw new InternalServerError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); @@ -421,350 +130,11 @@ public ApiClientHttpResponse deidentifyPresentation( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifySpreadsheet( - DeidentifyFileRequestDeidentifySpreadsheet request) { - return deidentifySpreadsheet(request, null); - } - - /** - * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifySpreadsheet( - DeidentifyFileRequestDeidentifySpreadsheet request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/spreadsheet") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyStructuredText( - DeidentifyFileRequestDeidentifyStructuredText request) { - return deidentifyStructuredText(request, null); - } - - /** - * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyStructuredText( - DeidentifyFileRequestDeidentifyStructuredText request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/structured_text") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyText(DeidentifyFileRequestDeidentifyText request) { - return deidentifyText(request, null); - } - - /** - * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. - */ - public ApiClientHttpResponse deidentifyText( - DeidentifyFileRequestDeidentifyText request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/file/text") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * Re-identifies tokens in a file. - */ - public ApiClientHttpResponse reidentifyFile(ReidentifyFileRequestReidentifyFile request) { - return reidentifyFile(request, null); - } - - /** - * Re-identifies tokens in a file. - */ - public ApiClientHttpResponse reidentifyFile( - ReidentifyFileRequestReidentifyFile request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/reidentify/file") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ReidentifyFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * Returns the status of a detect run. - */ - public ApiClientHttpResponse getRun(String runId) { - return getRun(runId, GetRunRequest.builder().build()); - } - - /** - * Returns the status of a detect run. - */ - public ApiClientHttpResponse getRun(String runId, GetRunRequest request) { - return getRun(runId, request, null); - } - - /** - * Returns the status of a detect run. - */ - public ApiClientHttpResponse getRun( - String runId, GetRunRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/runs") - .addPathSegment(runId); - if (request.getVaultId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "vault_id", request.getVaultId().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetectRunsResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileAudioRequestDeidentifyAudio.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileAudioRequestDeidentifyAudio.java deleted file mode 100644 index c2baa931..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileAudioRequestDeidentifyAudio.java +++ /dev/null @@ -1,663 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileAudioRequestDeidentifyAudioOutputTranscription; -import com.skyflow.generated.rest.types.FileDataDeidentifyAudio; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileAudioRequestDeidentifyAudio.Builder.class) -public final class DeidentifyFileAudioRequestDeidentifyAudio { - private final FileDataDeidentifyAudio file; - - private final String vaultId; - - private final Optional outputTranscription; - - private final Optional outputProcessedAudio; - - private final Optional bleepStartPadding; - - private final Optional bleepStopPadding; - - private final Optional bleepFrequency; - - private final Optional bleepGain; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileAudioRequestDeidentifyAudio( - FileDataDeidentifyAudio file, - String vaultId, - Optional outputTranscription, - Optional outputProcessedAudio, - Optional bleepStartPadding, - Optional bleepStopPadding, - Optional bleepFrequency, - Optional bleepGain, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.outputTranscription = outputTranscription; - this.outputProcessedAudio = outputProcessedAudio; - this.bleepStartPadding = bleepStartPadding; - this.bleepStopPadding = bleepStopPadding; - this.bleepFrequency = bleepFrequency; - this.bleepGain = bleepGain; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataDeidentifyAudio getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Type of transcription to output. - */ - @JsonProperty("output_transcription") - public Optional getOutputTranscription() { - return outputTranscription; - } - - /** - * @return Whether to include the processed audio file in the response. - */ - @JsonProperty("output_processed_audio") - public Optional getOutputProcessedAudio() { - return outputProcessedAudio; - } - - /** - * @return Padding added to the beginning of a bleep, in seconds. - */ - @JsonProperty("bleep_start_padding") - public Optional getBleepStartPadding() { - return bleepStartPadding; - } - - /** - * @return Padding added to the end of a bleep, in seconds. - */ - @JsonProperty("bleep_stop_padding") - public Optional getBleepStopPadding() { - return bleepStopPadding; - } - - /** - * @return The pitch of the bleep sound, in Hz. The higher the number, the higher the pitch. - */ - @JsonProperty("bleep_frequency") - public Optional getBleepFrequency() { - return bleepFrequency; - } - - /** - * @return Relative loudness of the bleep in dB. Positive values increase its loudness, and negative values decrease it. - */ - @JsonProperty("bleep_gain") - public Optional getBleepGain() { - return bleepGain; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileAudioRequestDeidentifyAudio - && equalTo((DeidentifyFileAudioRequestDeidentifyAudio) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileAudioRequestDeidentifyAudio other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && outputTranscription.equals(other.outputTranscription) - && outputProcessedAudio.equals(other.outputProcessedAudio) - && bleepStartPadding.equals(other.bleepStartPadding) - && bleepStopPadding.equals(other.bleepStopPadding) - && bleepFrequency.equals(other.bleepFrequency) - && bleepGain.equals(other.bleepGain) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.outputTranscription, - this.outputProcessedAudio, - this.bleepStartPadding, - this.bleepStopPadding, - this.bleepFrequency, - this.bleepGain, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataDeidentifyAudio file); - - Builder from(DeidentifyFileAudioRequestDeidentifyAudio other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileAudioRequestDeidentifyAudio build(); - - /** - *

Type of transcription to output.

- */ - _FinalStage outputTranscription( - Optional outputTranscription); - - _FinalStage outputTranscription( - DeidentifyFileAudioRequestDeidentifyAudioOutputTranscription outputTranscription); - - /** - *

Whether to include the processed audio file in the response.

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

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

- */ - _FinalStage bleepStartPadding(Optional bleepStartPadding); - - _FinalStage bleepStartPadding(Float bleepStartPadding); - - /** - *

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

- */ - _FinalStage bleepStopPadding(Optional bleepStopPadding); - - _FinalStage bleepStopPadding(Float bleepStopPadding); - - /** - *

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

- */ - _FinalStage bleepFrequency(Optional bleepFrequency); - - _FinalStage bleepFrequency(Integer bleepFrequency); - - /** - *

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

- */ - _FinalStage bleepGain(Optional bleepGain); - - _FinalStage bleepGain(Integer bleepGain); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes(Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataDeidentifyAudio file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = Optional.empty(); - - private Optional bleepGain = Optional.empty(); - - private Optional bleepFrequency = Optional.empty(); - - private Optional bleepStopPadding = Optional.empty(); - - private Optional bleepStartPadding = Optional.empty(); - - private Optional outputProcessedAudio = Optional.empty(); - - private Optional outputTranscription = - Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileAudioRequestDeidentifyAudio other) { - file(other.getFile()); - vaultId(other.getVaultId()); - outputTranscription(other.getOutputTranscription()); - outputProcessedAudio(other.getOutputProcessedAudio()); - bleepStartPadding(other.getBleepStartPadding()); - bleepStopPadding(other.getBleepStopPadding()); - bleepFrequency(other.getBleepFrequency()); - bleepGain(other.getBleepGain()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataDeidentifyAudio file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Whether to include the processed audio file in the response.

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

Whether to include the processed audio file in the response.

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

Type of transcription to output.

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

Type of transcription to output.

- */ - @Override - @JsonSetter(value = "output_transcription", nulls = Nulls.SKIP) - public _FinalStage outputTranscription( - Optional outputTranscription) { - this.outputTranscription = outputTranscription; - return this; - } - - @Override - public DeidentifyFileAudioRequestDeidentifyAudio build() { - return new DeidentifyFileAudioRequestDeidentifyAudio( - file, - vaultId, - outputTranscription, - outputProcessedAudio, - bleepStartPadding, - bleepStopPadding, - bleepFrequency, - bleepGain, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileDocumentPdfRequestDeidentifyPdf.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileDocumentPdfRequestDeidentifyPdf.java deleted file mode 100644 index 1844a116..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileDocumentPdfRequestDeidentifyPdf.java +++ /dev/null @@ -1,479 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem; -import com.skyflow.generated.rest.types.FileDataDeidentifyPdf; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileDocumentPdfRequestDeidentifyPdf.Builder.class) -public final class DeidentifyFileDocumentPdfRequestDeidentifyPdf { - private final FileDataDeidentifyPdf file; - - private final String vaultId; - - private final Optional density; - - private final Optional maxResolution; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileDocumentPdfRequestDeidentifyPdf( - FileDataDeidentifyPdf file, - String vaultId, - Optional density, - Optional maxResolution, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.density = density; - this.maxResolution = maxResolution; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataDeidentifyPdf getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Pixel density at which to process the PDF file. - */ - @JsonProperty("density") - public Optional getDensity() { - return density; - } - - /** - * @return Max resolution at which to process the PDF file. - */ - @JsonProperty("max_resolution") - public Optional getMaxResolution() { - return maxResolution; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileDocumentPdfRequestDeidentifyPdf - && equalTo((DeidentifyFileDocumentPdfRequestDeidentifyPdf) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileDocumentPdfRequestDeidentifyPdf other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && density.equals(other.density) - && maxResolution.equals(other.maxResolution) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.density, - this.maxResolution, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataDeidentifyPdf file); - - Builder from(DeidentifyFileDocumentPdfRequestDeidentifyPdf other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileDocumentPdfRequestDeidentifyPdf build(); - - /** - *

Pixel density at which to process the PDF file.

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

Max resolution at which to process the PDF file.

- */ - _FinalStage maxResolution(Optional maxResolution); - - _FinalStage maxResolution(Integer maxResolution); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes( - Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataDeidentifyPdf file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = - Optional.empty(); - - private Optional maxResolution = Optional.empty(); - - private Optional density = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileDocumentPdfRequestDeidentifyPdf other) { - file(other.getFile()); - vaultId(other.getVaultId()); - density(other.getDensity()); - maxResolution(other.getMaxResolution()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataDeidentifyPdf file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

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

Max resolution at which to process the PDF file.

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

Max resolution at which to process the PDF file.

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

Pixel density at which to process the PDF file.

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

Pixel density at which to process the PDF file.

- */ - @Override - @JsonSetter(value = "density", nulls = Nulls.SKIP) - public _FinalStage density(Optional density) { - this.density = density; - return this; - } - - @Override - public DeidentifyFileDocumentPdfRequestDeidentifyPdf build() { - return new DeidentifyFileDocumentPdfRequestDeidentifyPdf( - file, - vaultId, - density, - maxResolution, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileImageRequestDeidentifyImage.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileImageRequestDeidentifyImage.java deleted file mode 100644 index 25ddea9c..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileImageRequestDeidentifyImage.java +++ /dev/null @@ -1,524 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileImageRequestDeidentifyImageEntityTypesItem; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileImageRequestDeidentifyImageMaskingMethod; -import com.skyflow.generated.rest.types.FileDataDeidentifyImage; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileImageRequestDeidentifyImage.Builder.class) -public final class DeidentifyFileImageRequestDeidentifyImage { - private final FileDataDeidentifyImage file; - - private final String vaultId; - - private final Optional outputProcessedImage; - - private final Optional outputOcrText; - - private final Optional maskingMethod; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileImageRequestDeidentifyImage( - FileDataDeidentifyImage file, - String vaultId, - Optional outputProcessedImage, - Optional outputOcrText, - Optional maskingMethod, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.outputProcessedImage = outputProcessedImage; - this.outputOcrText = outputOcrText; - this.maskingMethod = maskingMethod; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataDeidentifyImage getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return If true, includes processed image in the output. - */ - @JsonProperty("output_processed_image") - public Optional getOutputProcessedImage() { - return outputProcessedImage; - } - - /** - * @return If true, includes text detected by OCR in the response. - */ - @JsonProperty("output_ocr_text") - public Optional getOutputOcrText() { - return outputOcrText; - } - - /** - * @return Method to mask the entities in the image. - */ - @JsonProperty("masking_method") - public Optional getMaskingMethod() { - return maskingMethod; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileImageRequestDeidentifyImage - && equalTo((DeidentifyFileImageRequestDeidentifyImage) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileImageRequestDeidentifyImage other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && outputProcessedImage.equals(other.outputProcessedImage) - && outputOcrText.equals(other.outputOcrText) - && maskingMethod.equals(other.maskingMethod) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.outputProcessedImage, - this.outputOcrText, - this.maskingMethod, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataDeidentifyImage file); - - Builder from(DeidentifyFileImageRequestDeidentifyImage other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileImageRequestDeidentifyImage build(); - - /** - *

If true, includes processed image in the output.

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

If true, includes text detected by OCR in the response.

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

Method to mask the entities in the image.

- */ - _FinalStage maskingMethod(Optional maskingMethod); - - _FinalStage maskingMethod(DeidentifyFileImageRequestDeidentifyImageMaskingMethod maskingMethod); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes(Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataDeidentifyImage file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = Optional.empty(); - - private Optional maskingMethod = Optional.empty(); - - private Optional outputOcrText = Optional.empty(); - - private Optional outputProcessedImage = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileImageRequestDeidentifyImage other) { - file(other.getFile()); - vaultId(other.getVaultId()); - outputProcessedImage(other.getOutputProcessedImage()); - outputOcrText(other.getOutputOcrText()); - maskingMethod(other.getMaskingMethod()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataDeidentifyImage file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

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

Method to mask the entities in the image.

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

Method to mask the entities in the image.

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

If true, includes text detected by OCR in the response.

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

If true, includes text detected by OCR in the response.

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

If true, includes processed image in the output.

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

If true, includes processed image in the output.

- */ - @Override - @JsonSetter(value = "output_processed_image", nulls = Nulls.SKIP) - public _FinalStage outputProcessedImage(Optional outputProcessedImage) { - this.outputProcessedImage = outputProcessedImage; - return this; - } - - @Override - public DeidentifyFileImageRequestDeidentifyImage build() { - return new DeidentifyFileImageRequestDeidentifyImage( - file, - vaultId, - outputProcessedImage, - outputOcrText, - maskingMethod, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java deleted file mode 100644 index 62d77229..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java +++ /dev/null @@ -1,385 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileRequestEntityTypesItem; -import com.skyflow.generated.rest.types.FileData; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileRequest.Builder.class) -public final class DeidentifyFileRequest { - private final FileData file; - - private final String vaultId; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileRequest( - FileData file, - String vaultId, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileData getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileRequest && equalTo((DeidentifyFileRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileRequest other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileData file); - - Builder from(DeidentifyFileRequest other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileRequest build(); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes(Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileData file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileRequest other) { - file(other.getFile()); - vaultId(other.getVaultId()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileData file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

- */ - @Override - @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) - public _FinalStage entityTypes(Optional> entityTypes) { - this.entityTypes = entityTypes; - return this; - } - - @Override - public DeidentifyFileRequest build() { - return new DeidentifyFileRequest( - file, - vaultId, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyDocument.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyDocument.java deleted file mode 100644 index c4d9841d..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyDocument.java +++ /dev/null @@ -1,387 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileRequestDeidentifyDocumentEntityTypesItem; -import com.skyflow.generated.rest.types.FileDataDeidentifyDocument; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileRequestDeidentifyDocument.Builder.class) -public final class DeidentifyFileRequestDeidentifyDocument { - private final FileDataDeidentifyDocument file; - - private final String vaultId; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileRequestDeidentifyDocument( - FileDataDeidentifyDocument file, - String vaultId, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataDeidentifyDocument getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileRequestDeidentifyDocument - && equalTo((DeidentifyFileRequestDeidentifyDocument) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileRequestDeidentifyDocument other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataDeidentifyDocument file); - - Builder from(DeidentifyFileRequestDeidentifyDocument other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileRequestDeidentifyDocument build(); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes(Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataDeidentifyDocument file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileRequestDeidentifyDocument other) { - file(other.getFile()); - vaultId(other.getVaultId()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataDeidentifyDocument file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

- */ - @Override - @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) - public _FinalStage entityTypes( - Optional> entityTypes) { - this.entityTypes = entityTypes; - return this; - } - - @Override - public DeidentifyFileRequestDeidentifyDocument build() { - return new DeidentifyFileRequestDeidentifyDocument( - file, - vaultId, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyPresentation.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyPresentation.java deleted file mode 100644 index e1cea77f..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyPresentation.java +++ /dev/null @@ -1,388 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileRequestDeidentifyPresentationEntityTypesItem; -import com.skyflow.generated.rest.types.FileDataDeidentifyPresentation; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileRequestDeidentifyPresentation.Builder.class) -public final class DeidentifyFileRequestDeidentifyPresentation { - private final FileDataDeidentifyPresentation file; - - private final String vaultId; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileRequestDeidentifyPresentation( - FileDataDeidentifyPresentation file, - String vaultId, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataDeidentifyPresentation getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileRequestDeidentifyPresentation - && equalTo((DeidentifyFileRequestDeidentifyPresentation) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileRequestDeidentifyPresentation other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataDeidentifyPresentation file); - - Builder from(DeidentifyFileRequestDeidentifyPresentation other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileRequestDeidentifyPresentation build(); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes(Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataDeidentifyPresentation file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = - Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileRequestDeidentifyPresentation other) { - file(other.getFile()); - vaultId(other.getVaultId()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataDeidentifyPresentation file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

- */ - @Override - @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) - public _FinalStage entityTypes( - Optional> entityTypes) { - this.entityTypes = entityTypes; - return this; - } - - @Override - public DeidentifyFileRequestDeidentifyPresentation build() { - return new DeidentifyFileRequestDeidentifyPresentation( - file, - vaultId, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifySpreadsheet.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifySpreadsheet.java deleted file mode 100644 index 10ca8feb..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifySpreadsheet.java +++ /dev/null @@ -1,388 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileRequestDeidentifySpreadsheetEntityTypesItem; -import com.skyflow.generated.rest.types.FileDataDeidentifySpreadsheet; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileRequestDeidentifySpreadsheet.Builder.class) -public final class DeidentifyFileRequestDeidentifySpreadsheet { - private final FileDataDeidentifySpreadsheet file; - - private final String vaultId; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileRequestDeidentifySpreadsheet( - FileDataDeidentifySpreadsheet file, - String vaultId, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataDeidentifySpreadsheet getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileRequestDeidentifySpreadsheet - && equalTo((DeidentifyFileRequestDeidentifySpreadsheet) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileRequestDeidentifySpreadsheet other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataDeidentifySpreadsheet file); - - Builder from(DeidentifyFileRequestDeidentifySpreadsheet other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileRequestDeidentifySpreadsheet build(); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes(Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataDeidentifySpreadsheet file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = - Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileRequestDeidentifySpreadsheet other) { - file(other.getFile()); - vaultId(other.getVaultId()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataDeidentifySpreadsheet file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

- */ - @Override - @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) - public _FinalStage entityTypes( - Optional> entityTypes) { - this.entityTypes = entityTypes; - return this; - } - - @Override - public DeidentifyFileRequestDeidentifySpreadsheet build() { - return new DeidentifyFileRequestDeidentifySpreadsheet( - file, - vaultId, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyStructuredText.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyStructuredText.java deleted file mode 100644 index e3f555b8..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyStructuredText.java +++ /dev/null @@ -1,389 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileRequestDeidentifyStructuredTextEntityTypesItem; -import com.skyflow.generated.rest.types.FileDataDeidentifyStructuredText; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileRequestDeidentifyStructuredText.Builder.class) -public final class DeidentifyFileRequestDeidentifyStructuredText { - private final FileDataDeidentifyStructuredText file; - - private final String vaultId; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileRequestDeidentifyStructuredText( - FileDataDeidentifyStructuredText file, - String vaultId, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataDeidentifyStructuredText getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileRequestDeidentifyStructuredText - && equalTo((DeidentifyFileRequestDeidentifyStructuredText) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileRequestDeidentifyStructuredText other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataDeidentifyStructuredText file); - - Builder from(DeidentifyFileRequestDeidentifyStructuredText other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileRequestDeidentifyStructuredText build(); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes( - Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataDeidentifyStructuredText file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = - Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileRequestDeidentifyStructuredText other) { - file(other.getFile()); - vaultId(other.getVaultId()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataDeidentifyStructuredText file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

- */ - @Override - @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) - public _FinalStage entityTypes( - Optional> entityTypes) { - this.entityTypes = entityTypes; - return this; - } - - @Override - public DeidentifyFileRequestDeidentifyStructuredText build() { - return new DeidentifyFileRequestDeidentifyStructuredText( - file, - vaultId, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyText.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyText.java deleted file mode 100644 index 8457c790..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequestDeidentifyText.java +++ /dev/null @@ -1,386 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.files.types.DeidentifyFileRequestDeidentifyTextEntityTypesItem; -import com.skyflow.generated.rest.types.FileDataDeidentifyText; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyFileRequestDeidentifyText.Builder.class) -public final class DeidentifyFileRequestDeidentifyText { - private final FileDataDeidentifyText file; - - private final String vaultId; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyFileRequestDeidentifyText( - FileDataDeidentifyText file, - String vaultId, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataDeidentifyText getFile() { - return file; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyFileRequestDeidentifyText - && equalTo((DeidentifyFileRequestDeidentifyText) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyFileRequestDeidentifyText other) { - return file.equals(other.file) - && vaultId.equals(other.vaultId) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.file, - this.vaultId, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataDeidentifyText file); - - Builder from(DeidentifyFileRequestDeidentifyText other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyFileRequestDeidentifyText build(); - - /** - *

Entities to detect and de-identify.

- */ - _FinalStage entityTypes(Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataDeidentifyText file; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyFileRequestDeidentifyText other) { - file(other.getFile()); - vaultId(other.getVaultId()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataDeidentifyText file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

- */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

Entities to detect and de-identify.

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

Entities to detect and de-identify.

- */ - @Override - @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) - public _FinalStage entityTypes(Optional> entityTypes) { - this.entityTypes = entityTypes; - return this; - } - - @Override - public DeidentifyFileRequestDeidentifyText build() { - return new DeidentifyFileRequestDeidentifyText( - file, - vaultId, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/FileDeleteRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/FileDeleteRequest.java new file mode 100644 index 00000000..50fdb91c --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/FileDeleteRequest.java @@ -0,0 +1,191 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.FileDeleteRecord; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileDeleteRequest.Builder.class) +public final class FileDeleteRequest { + private final String vaultId; + + private final List records; + + private final Map additionalProperties; + + private FileDeleteRequest( + String vaultId, List records, Map additionalProperties) { + this.vaultId = vaultId; + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return List of record objects (max 20,000) identifying the file columns to delete. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileDeleteRequest && equalTo((FileDeleteRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileDeleteRequest other) { + return vaultId.equals(other.vaultId) && records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

ID of the vault.

+ */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(FileDeleteRequest other); + } + + public interface _FinalStage { + FileDeleteRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

List of record objects (max 20,000) identifying the file columns to delete.

+ */ + _FinalStage records(List records); + + _FinalStage addRecords(FileDeleteRecord records); + + _FinalStage addAllRecords(List records); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(FileDeleteRequest other) { + vaultId(other.getVaultId()); + records(other.getRecords()); + return this; + } + + /** + *

ID of the vault.

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

List of record objects (max 20,000) identifying the file columns to delete.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + /** + *

List of record objects (max 20,000) identifying the file columns to delete.

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

List of record objects (max 20,000) identifying the file columns to delete.

+ */ + @java.lang.Override + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public _FinalStage records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + @java.lang.Override + public FileDeleteRequest build() { + return new FileDeleteRequest(vaultId, records, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/FileUploadRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/FileUploadRequest.java new file mode 100644 index 00000000..0db8c62b --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/FileUploadRequest.java @@ -0,0 +1,191 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.FileUploadRecord; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileUploadRequest.Builder.class) +public final class FileUploadRequest { + private final String vaultId; + + private final List records; + + private final Map additionalProperties; + + private FileUploadRequest( + String vaultId, List records, Map additionalProperties) { + this.vaultId = vaultId; + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return List of records for which signed file upload URLs are requested. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileUploadRequest && equalTo((FileUploadRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileUploadRequest other) { + return vaultId.equals(other.vaultId) && records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

ID of the vault.

+ */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(FileUploadRequest other); + } + + public interface _FinalStage { + FileUploadRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

List of records for which signed file upload URLs are requested.

+ */ + _FinalStage records(List records); + + _FinalStage addRecords(FileUploadRecord records); + + _FinalStage addAllRecords(List records); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(FileUploadRequest other) { + vaultId(other.getVaultId()); + records(other.getRecords()); + return this; + } + + /** + *

ID of the vault.

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

List of records for which signed file upload URLs are requested.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + /** + *

List of records for which signed file upload URLs are requested.

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

List of records for which signed file upload URLs are requested.

+ */ + @java.lang.Override + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public _FinalStage records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + @java.lang.Override + public FileUploadRequest build() { + return new FileUploadRequest(vaultId, records, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/GetRunRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/GetRunRequest.java deleted file mode 100644 index cde24227..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/GetRunRequest.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = GetRunRequest.Builder.class) -public final class GetRunRequest { - private final Optional vaultId; - - private final Map additionalProperties; - - private GetRunRequest(Optional vaultId, Map additionalProperties) { - this.vaultId = vaultId; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("vault_id") - public Optional getVaultId() { - return vaultId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof GetRunRequest && equalTo((GetRunRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(GetRunRequest other) { - return vaultId.equals(other.vaultId); - } - - @Override - public int hashCode() { - return Objects.hash(this.vaultId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional vaultId = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(GetRunRequest other) { - vaultId(other.getVaultId()); - return this; - } - - @JsonSetter(value = "vault_id", nulls = Nulls.SKIP) - public Builder vaultId(Optional vaultId) { - this.vaultId = vaultId; - return this; - } - - public Builder vaultId(String vaultId) { - this.vaultId = Optional.ofNullable(vaultId); - return this; - } - - public GetRunRequest build() { - return new GetRunRequest(vaultId, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequestReidentifyFile.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequestReidentifyFile.java deleted file mode 100644 index 5cd22747..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequestReidentifyFile.java +++ /dev/null @@ -1,166 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.types.FileDataReidentifyFile; -import com.skyflow.generated.rest.types.Format; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = ReidentifyFileRequestReidentifyFile.Builder.class) -public final class ReidentifyFileRequestReidentifyFile { - private final FileDataReidentifyFile file; - - private final String vaultId; - - private final Optional format; - - private final Map additionalProperties; - - private ReidentifyFileRequestReidentifyFile( - FileDataReidentifyFile file, - String vaultId, - Optional format, - Map additionalProperties) { - this.file = file; - this.vaultId = vaultId; - this.format = format; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("file") - public FileDataReidentifyFile getFile() { - return file; - } - - /** - * @return ID of the vault where the entities are stored. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - @JsonProperty("format") - public Optional getFormat() { - return format; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof ReidentifyFileRequestReidentifyFile - && equalTo((ReidentifyFileRequestReidentifyFile) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(ReidentifyFileRequestReidentifyFile other) { - return file.equals(other.file) && vaultId.equals(other.vaultId) && format.equals(other.format); - } - - @Override - public int hashCode() { - return Objects.hash(this.file, this.vaultId, this.format); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - VaultIdStage file(@NotNull FileDataReidentifyFile file); - - Builder from(ReidentifyFileRequestReidentifyFile other); - } - - public interface VaultIdStage { - /** - * ID of the vault where the entities are stored. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - ReidentifyFileRequestReidentifyFile build(); - - _FinalStage format(Optional format); - - _FinalStage format(Format format); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, VaultIdStage, _FinalStage { - private FileDataReidentifyFile file; - - private String vaultId; - - private Optional format = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(ReidentifyFileRequestReidentifyFile other) { - file(other.getFile()); - vaultId(other.getVaultId()); - format(other.getFormat()); - return this; - } - - @Override - @JsonSetter("file") - public VaultIdStage file(@NotNull FileDataReidentifyFile file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - /** - * ID of the vault where the entities are stored.

ID of the vault where the entities are stored.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @Override - @JsonSetter("vault_id") - public _FinalStage vaultId(@NotNull String vaultId) { - this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); - return this; - } - - @Override - public _FinalStage format(Format format) { - this.format = Optional.ofNullable(format); - return this; - } - - @Override - @JsonSetter(value = "format", nulls = Nulls.SKIP) - public _FinalStage format(Optional format) { - this.format = format; - return this; - } - - @Override - public ReidentifyFileRequestReidentifyFile build() { - return new ReidentifyFileRequestReidentifyFile(file, vaultId, format, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UploadFileV2Request.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/UploadFileRequestV2.java similarity index 70% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UploadFileV2Request.java rename to skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/UploadFileRequestV2.java index 81a9f837..6979c78b 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UploadFileV2Request.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/requests/UploadFileRequestV2.java @@ -1,21 +1,26 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.resources.records.requests; - -import com.fasterxml.jackson.annotation.*; +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; -import org.jetbrains.annotations.NotNull; - import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; +import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = UploadFileV2Request.Builder.class) -public final class UploadFileV2Request { +@JsonDeserialize(builder = UploadFileRequestV2.Builder.class) +public final class UploadFileRequestV2 { private final String tableName; private final String columnName; @@ -26,7 +31,7 @@ public final class UploadFileV2Request { private final Map additionalProperties; - private UploadFileV2Request( + private UploadFileRequestV2( String tableName, String columnName, Optional skyflowId, @@ -40,7 +45,7 @@ private UploadFileV2Request( } /** - * @return Name of the table to upload the file to. + * @return Name of the table. */ @JsonProperty("tableName") public String getTableName() { @@ -48,7 +53,7 @@ public String getTableName() { } /** - * @return Name of the column to upload the file to. The column must have a file data type. + * @return Name of the column that contains the file. */ @JsonProperty("columnName") public String getColumnName() { @@ -56,7 +61,7 @@ public String getColumnName() { } /** - * @return Skyflow ID of the record to upload the file to. If skyflowID isn't specified, a new record will be created. + * @return ID of the record to update. */ @JsonProperty("skyflowID") public Optional getSkyflowId() { @@ -71,10 +76,10 @@ public Optional getReturnFileMetadata() { return returnFileMetadata; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof UploadFileV2Request && equalTo((UploadFileV2Request) other); + return other instanceof UploadFileRequestV2 && equalTo((UploadFileRequestV2) other); } @JsonAnyGetter @@ -82,19 +87,19 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(UploadFileV2Request other) { + private boolean equalTo(UploadFileRequestV2 other) { return tableName.equals(other.tableName) && columnName.equals(other.columnName) && skyflowId.equals(other.skyflowId) && returnFileMetadata.equals(other.returnFileMetadata); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.tableName, this.columnName, this.skyflowId, this.returnFileMetadata); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -105,25 +110,29 @@ public static TableNameStage builder() { public interface TableNameStage { /** - * Name of the table to upload the file to. + *

Name of the table.

*/ ColumnNameStage tableName(@NotNull String tableName); - Builder from(UploadFileV2Request other); + Builder from(UploadFileRequestV2 other); } public interface ColumnNameStage { /** - * Name of the column to upload the file to. The column must have a `file` data type. + *

Name of the column that contains the file.

*/ _FinalStage columnName(@NotNull String columnName); } public interface _FinalStage { - UploadFileV2Request build(); + UploadFileRequestV2 build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); /** - *

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

+ *

ID of the record to update.

*/ _FinalStage skyflowId(Optional skyflowId); @@ -152,8 +161,8 @@ public static final class Builder implements TableNameStage, ColumnNameStage, _F private Builder() {} - @Override - public Builder from(UploadFileV2Request other) { + @java.lang.Override + public Builder from(UploadFileRequestV2 other) { tableName(other.getTableName()); columnName(other.getColumnName()); skyflowId(other.getSkyflowId()); @@ -162,10 +171,10 @@ public Builder from(UploadFileV2Request other) { } /** - * Name of the table to upload the file to.

Name of the table to upload the file to.

+ *

Name of the table.

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

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

+ *

Name of the column that contains the file.

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

If true, returns metadata about the uploaded file.

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

If true, returns metadata about the uploaded file.

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

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

+ *

ID of the record to update.

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

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

+ *

ID of the record to update.

*/ - @Override + @java.lang.Override @JsonSetter(value = "skyflowID", nulls = Nulls.SKIP) public _FinalStage skyflowId(Optional skyflowId) { this.skyflowId = skyflowId; return this; } - @Override - public UploadFileV2Request build() { - return new UploadFileV2Request(tableName, columnName, skyflowId, returnFileMetadata, additionalProperties); + @java.lang.Override + public UploadFileRequestV2 build() { + return new UploadFileRequestV2( + tableName, columnName, skyflowId, returnFileMetadata, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem.java deleted file mode 100644 index 0335ac47..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileAudioRequestDeidentifyAudioEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileAudioRequestDeidentifyAudioOutputTranscription.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileAudioRequestDeidentifyAudioOutputTranscription.java deleted file mode 100644 index 22a948ca..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileAudioRequestDeidentifyAudioOutputTranscription.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileAudioRequestDeidentifyAudioOutputTranscription { - TRANSCRIPTION("transcription"), - - MEDICAL_TRANSCRIPTION("medical_transcription"), - - DIARIZED_TRANSCRIPTION("diarized_transcription"), - - MEDICAL_DIARIZED_TRANSCRIPTION("medical_diarized_transcription"); - - private final String value; - - DeidentifyFileAudioRequestDeidentifyAudioOutputTranscription(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem.java deleted file mode 100644 index aa6c578d..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileDocumentPdfRequestDeidentifyPdfEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileImageRequestDeidentifyImageEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileImageRequestDeidentifyImageEntityTypesItem.java deleted file mode 100644 index 5e08b9db..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileImageRequestDeidentifyImageEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileImageRequestDeidentifyImageEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileImageRequestDeidentifyImageEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileImageRequestDeidentifyImageMaskingMethod.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileImageRequestDeidentifyImageMaskingMethod.java deleted file mode 100644 index d97b3191..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileImageRequestDeidentifyImageMaskingMethod.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileImageRequestDeidentifyImageMaskingMethod { - BLUR("blur"), - - BLACKBOX("blackbox"); - - private final String value; - - DeidentifyFileImageRequestDeidentifyImageMaskingMethod(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyDocumentEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyDocumentEntityTypesItem.java deleted file mode 100644 index 5089bc83..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyDocumentEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileRequestDeidentifyDocumentEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileRequestDeidentifyDocumentEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyPresentationEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyPresentationEntityTypesItem.java deleted file mode 100644 index a7682795..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyPresentationEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileRequestDeidentifyPresentationEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileRequestDeidentifyPresentationEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifySpreadsheetEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifySpreadsheetEntityTypesItem.java deleted file mode 100644 index 96a55f5a..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifySpreadsheetEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileRequestDeidentifySpreadsheetEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileRequestDeidentifySpreadsheetEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyStructuredTextEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyStructuredTextEntityTypesItem.java deleted file mode 100644 index aff014d8..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyStructuredTextEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileRequestDeidentifyStructuredTextEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileRequestDeidentifyStructuredTextEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyTextEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyTextEntityTypesItem.java deleted file mode 100644 index b0326561..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestDeidentifyTextEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileRequestDeidentifyTextEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileRequestDeidentifyTextEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestEntityTypesItem.java deleted file mode 100644 index 9c9c84c2..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.files.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyFileRequestEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyFileRequestEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncGuardrailsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncGuardrailsClient.java deleted file mode 100644 index fa45ee60..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncGuardrailsClient.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.guardrails; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.guardrails.requests.DetectGuardrailsRequest; -import com.skyflow.generated.rest.types.DetectGuardrailsResponse; - -import java.util.concurrent.CompletableFuture; - -public class AsyncGuardrailsClient { - protected final ClientOptions clientOptions; - - private final AsyncRawGuardrailsClient rawClient; - - public AsyncGuardrailsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawGuardrailsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawGuardrailsClient withRawResponse() { - return this.rawClient; - } - - /** - * Preserve safety and compliance with usage policies. - */ - public CompletableFuture checkGuardrails(DetectGuardrailsRequest request) { - return this.rawClient.checkGuardrails(request).thenApply(response -> response.body()); - } - - /** - * Preserve safety and compliance with usage policies. - */ - public CompletableFuture checkGuardrails( - DetectGuardrailsRequest request, RequestOptions requestOptions) { - return this.rawClient.checkGuardrails(request, requestOptions).thenApply(response -> response.body()); - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/GuardrailsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/GuardrailsClient.java deleted file mode 100644 index 5068196c..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/GuardrailsClient.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.guardrails; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.guardrails.requests.DetectGuardrailsRequest; -import com.skyflow.generated.rest.types.DetectGuardrailsResponse; - -public class GuardrailsClient { - protected final ClientOptions clientOptions; - - private final RawGuardrailsClient rawClient; - - public GuardrailsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new RawGuardrailsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawGuardrailsClient withRawResponse() { - return this.rawClient; - } - - /** - * Preserve safety and compliance with usage policies. - */ - public DetectGuardrailsResponse checkGuardrails(DetectGuardrailsRequest request) { - return this.rawClient.checkGuardrails(request).body(); - } - - /** - * Preserve safety and compliance with usage policies. - */ - public DetectGuardrailsResponse checkGuardrails(DetectGuardrailsRequest request, RequestOptions requestOptions) { - return this.rawClient.checkGuardrails(request, requestOptions).body(); - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/RawGuardrailsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/RawGuardrailsClient.java deleted file mode 100644 index 5bf5c31a..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/guardrails/RawGuardrailsClient.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.guardrails; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.BadRequestError; -import com.skyflow.generated.rest.errors.InternalServerError; -import com.skyflow.generated.rest.errors.UnauthorizedError; -import com.skyflow.generated.rest.resources.guardrails.requests.DetectGuardrailsRequest; -import com.skyflow.generated.rest.types.DetectGuardrailsResponse; -import com.skyflow.generated.rest.types.ErrorResponse; -import okhttp3.*; - -import java.io.IOException; - -public class RawGuardrailsClient { - protected final ClientOptions clientOptions; - - public RawGuardrailsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Preserve safety and compliance with usage policies. - */ - public ApiClientHttpResponse checkGuardrails(DetectGuardrailsRequest request) { - return checkGuardrails(request, null); - } - - /** - * Preserve safety and compliance with usage policies. - */ - public ApiClientHttpResponse checkGuardrails( - DetectGuardrailsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/guardrails") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetectGuardrailsResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/AsyncQueryClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/AsyncQueryClient.java index cab967a7..e2f24865 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/AsyncQueryClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/AsyncQueryClient.java @@ -5,9 +5,8 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; -import com.skyflow.generated.rest.types.V1GetQueryResponse; - +import com.skyflow.generated.rest.resources.query.requests.GetQueryRequest; +import com.skyflow.generated.rest.types.GetQueryResponse; import java.util.concurrent.CompletableFuture; public class AsyncQueryClient { @@ -28,27 +27,17 @@ public AsyncRawQueryClient withRawResponse() { } /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> - */ - public CompletableFuture queryServiceExecuteQuery(String vaultId) { - return this.rawClient.queryServiceExecuteQuery(vaultId).thenApply(response -> response.body()); - } - - /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + * Returns records for a valid SQL query. This endpoint
  • Can return redacted record values.
  • Supports only the SELECT command.
  • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
  • Can't modify the vault or perform transactions.
  • Can't return tokens.
  • Can't return file download or render URLs.
  • Doesn't support the WHERE keyword with columns using transient tokenization.
  • Doesn't support ? conditional for columns with column-level encryption disabled.
    • */ - public CompletableFuture queryServiceExecuteQuery( - String vaultId, QueryServiceExecuteQueryBody request) { - return this.rawClient.queryServiceExecuteQuery(vaultId, request).thenApply(response -> response.body()); + public CompletableFuture executeQuery(String vaultId, GetQueryRequest request) { + return this.rawClient.executeQuery(vaultId, request).thenApply(response -> response.body()); } /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + * Returns records for a valid SQL query. This endpoint
      • Can return redacted record values.
      • Supports only the SELECT command.
      • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
      • Can't modify the vault or perform transactions.
      • Can't return tokens.
      • Can't return file download or render URLs.
      • Doesn't support the WHERE keyword with columns using transient tokenization.
      • Doesn't support ? conditional for columns with column-level encryption disabled.
        • */ - public CompletableFuture queryServiceExecuteQuery( - String vaultId, QueryServiceExecuteQueryBody request, RequestOptions requestOptions) { - return this.rawClient - .queryServiceExecuteQuery(vaultId, request, requestOptions) - .thenApply(response -> response.body()); + public CompletableFuture executeQuery( + String vaultId, GetQueryRequest request, RequestOptions requestOptions) { + return this.rawClient.executeQuery(vaultId, request, requestOptions).thenApply(response -> response.body()); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/AsyncRawQueryClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/AsyncRawQueryClient.java index 7b8c9383..dbd40180 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/AsyncRawQueryClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/AsyncRawQueryClient.java @@ -4,15 +4,32 @@ package com.skyflow.generated.rest.resources.query; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; -import com.skyflow.generated.rest.types.V1GetQueryResponse; -import okhttp3.*; -import org.jetbrains.annotations.NotNull; - +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.query.requests.GetQueryRequest; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.GetQueryResponse; import java.io.IOException; import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; public class AsyncRawQueryClient { protected final ClientOptions clientOptions; @@ -22,32 +39,28 @@ public AsyncRawQueryClient(ClientOptions clientOptions) { } /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> - */ - public CompletableFuture> queryServiceExecuteQuery(String vaultId) { - return queryServiceExecuteQuery( - vaultId, QueryServiceExecuteQueryBody.builder().build()); - } - - /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + * Returns records for a valid SQL query. This endpoint
          • Can return redacted record values.
          • Supports only the SELECT command.
          • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
          • Can't modify the vault or perform transactions.
          • Can't return tokens.
          • Can't return file download or render URLs.
          • Doesn't support the WHERE keyword with columns using transient tokenization.
          • Doesn't support ? conditional for columns with column-level encryption disabled.
            • */ - public CompletableFuture> queryServiceExecuteQuery( - String vaultId, QueryServiceExecuteQueryBody request) { - return queryServiceExecuteQuery(vaultId, request, null); + public CompletableFuture> executeQuery( + String vaultId, GetQueryRequest request) { + return executeQuery(vaultId, request, null); } /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + * Returns records for a valid SQL query. This endpoint
              • Can return redacted record values.
              • Supports only the SELECT command.
              • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
              • Can't modify the vault or perform transactions.
              • Can't return tokens.
              • Can't return file download or render URLs.
              • Doesn't support the WHERE keyword with columns using transient tokenization.
              • Doesn't support ? conditional for columns with column-level encryption disabled.
                • */ - public CompletableFuture> queryServiceExecuteQuery( - String vaultId, QueryServiceExecuteQueryBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> executeQuery( + String vaultId, GetQueryRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegments("query") - .build(); + .addPathSegments("query"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -56,7 +69,7 @@ public CompletableFuture> queryService throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -66,33 +79,55 @@ public CompletableFuture> queryService if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1GetQueryResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetQueryResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/QueryClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/QueryClient.java index 39bb709d..f0444e50 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/QueryClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/QueryClient.java @@ -5,8 +5,8 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; -import com.skyflow.generated.rest.types.V1GetQueryResponse; +import com.skyflow.generated.rest.resources.query.requests.GetQueryRequest; +import com.skyflow.generated.rest.types.GetQueryResponse; public class QueryClient { protected final ClientOptions clientOptions; @@ -26,26 +26,16 @@ public RawQueryClient withRawResponse() { } /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + * Returns records for a valid SQL query. This endpoint
                  • Can return redacted record values.
                  • Supports only the SELECT command.
                  • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
                  • Can't modify the vault or perform transactions.
                  • Can't return tokens.
                  • Can't return file download or render URLs.
                  • Doesn't support the WHERE keyword with columns using transient tokenization.
                  • Doesn't support ? conditional for columns with column-level encryption disabled.
                    • */ - public V1GetQueryResponse queryServiceExecuteQuery(String vaultId) { - return this.rawClient.queryServiceExecuteQuery(vaultId).body(); + public GetQueryResponse executeQuery(String vaultId, GetQueryRequest request) { + return this.rawClient.executeQuery(vaultId, request).body(); } /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + * Returns records for a valid SQL query. This endpoint
                      • Can return redacted record values.
                      • Supports only the SELECT command.
                      • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
                      • Can't modify the vault or perform transactions.
                      • Can't return tokens.
                      • Can't return file download or render URLs.
                      • Doesn't support the WHERE keyword with columns using transient tokenization.
                      • Doesn't support ? conditional for columns with column-level encryption disabled.
                        • */ - public V1GetQueryResponse queryServiceExecuteQuery(String vaultId, QueryServiceExecuteQueryBody request) { - return this.rawClient.queryServiceExecuteQuery(vaultId, request).body(); - } - - /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> - */ - public V1GetQueryResponse queryServiceExecuteQuery( - String vaultId, QueryServiceExecuteQueryBody request, RequestOptions requestOptions) { - return this.rawClient - .queryServiceExecuteQuery(vaultId, request, requestOptions) - .body(); + public GetQueryResponse executeQuery(String vaultId, GetQueryRequest request, RequestOptions requestOptions) { + return this.rawClient.executeQuery(vaultId, request, requestOptions).body(); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/RawQueryClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/RawQueryClient.java index ec88ae93..a63af329 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/RawQueryClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/RawQueryClient.java @@ -4,13 +4,28 @@ package com.skyflow.generated.rest.resources.query; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; -import com.skyflow.generated.rest.types.V1GetQueryResponse; -import okhttp3.*; - +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.query.requests.GetQueryRequest; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.GetQueryResponse; import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class RawQueryClient { protected final ClientOptions clientOptions; @@ -20,32 +35,27 @@ public RawQueryClient(ClientOptions clientOptions) { } /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> - */ - public ApiClientHttpResponse queryServiceExecuteQuery(String vaultId) { - return queryServiceExecuteQuery( - vaultId, QueryServiceExecuteQueryBody.builder().build()); - } - - /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + * Returns records for a valid SQL query. This endpoint
                          • Can return redacted record values.
                          • Supports only the SELECT command.
                          • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
                          • Can't modify the vault or perform transactions.
                          • Can't return tokens.
                          • Can't return file download or render URLs.
                          • Doesn't support the WHERE keyword with columns using transient tokenization.
                          • Doesn't support ? conditional for columns with column-level encryption disabled.
                            • */ - public ApiClientHttpResponse queryServiceExecuteQuery( - String vaultId, QueryServiceExecuteQueryBody request) { - return queryServiceExecuteQuery(vaultId, request, null); + public ApiClientHttpResponse executeQuery(String vaultId, GetQueryRequest request) { + return executeQuery(vaultId, request, null); } /** - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + * Returns records for a valid SQL query. This endpoint
                              • Can return redacted record values.
                              • Supports only the SELECT command.
                              • Returns a maximum of 25 records. To return additional records, perform another query using the OFFSET keyword.
                              • Can't modify the vault or perform transactions.
                              • Can't return tokens.
                              • Can't return file download or render URLs.
                              • Doesn't support the WHERE keyword with columns using transient tokenization.
                              • Doesn't support ? conditional for columns with column-level encryption disabled.
                                • */ - public ApiClientHttpResponse queryServiceExecuteQuery( - String vaultId, QueryServiceExecuteQueryBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse executeQuery( + String vaultId, GetQueryRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegments("query") - .build(); + .addPathSegments("query"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -54,7 +64,7 @@ public ApiClientHttpResponse queryServiceExecuteQuery( throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -64,26 +74,42 @@ public ApiClientHttpResponse queryServiceExecuteQuery( if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1GetQueryResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetQueryResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/ExecuteQueryRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/ExecuteQueryRequest.java new file mode 100644 index 00000000..2d9c81c0 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/ExecuteQueryRequest.java @@ -0,0 +1,160 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.query.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ExecuteQueryRequest.Builder.class) +public final class ExecuteQueryRequest { + private final String vaultId; + + private final String query; + + private final Map additionalProperties; + + private ExecuteQueryRequest(String vaultId, String query, Map additionalProperties) { + this.vaultId = vaultId; + this.query = query; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault where the query is being performed. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Query to perform. + */ + @JsonProperty("query") + public String getQuery() { + return query; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ExecuteQueryRequest && equalTo((ExecuteQueryRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ExecuteQueryRequest other) { + return vaultId.equals(other.vaultId) && query.equals(other.query); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.query); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault where the query is being performed.

                                  + */ + QueryStage vaultId(@NotNull String vaultId); + + Builder from(ExecuteQueryRequest other); + } + + public interface QueryStage { + /** + *

                                  Query to perform.

                                  + */ + _FinalStage query(@NotNull String query); + } + + public interface _FinalStage { + ExecuteQueryRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, QueryStage, _FinalStage { + private String vaultId; + + private String query; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ExecuteQueryRequest other) { + vaultId(other.getVaultId()); + query(other.getQuery()); + return this; + } + + /** + *

                                  ID of the vault where the query is being performed.

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

                                  Query to perform.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("query") + public _FinalStage query(@NotNull String query) { + this.query = Objects.requireNonNull(query, "query must not be null"); + return this; + } + + @java.lang.Override + public ExecuteQueryRequest build() { + return new ExecuteQueryRequest(vaultId, query, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/GetQueryRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/GetQueryRequest.java new file mode 100644 index 00000000..03e15fa6 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/GetQueryRequest.java @@ -0,0 +1,128 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.query.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetQueryRequest.Builder.class) +public final class GetQueryRequest { + private final String query; + + private final Map additionalProperties; + + private GetQueryRequest(String query, Map additionalProperties) { + this.query = query; + this.additionalProperties = additionalProperties; + } + + /** + * @return The SQL query to execute.

                                  Supported commands:
                                  • SELECT
                                  Supported operators:
                                  • >
                                  • <
                                  • =
                                  • AND
                                  • OR
                                  • NOT
                                  • LIKE
                                  • ILIKE
                                  • NULL
                                  • NOT NULL
                                  Supported keywords:
                                  • FROM
                                  • JOIN
                                  • INNER JOIN
                                  • LEFT OUTER JOIN
                                  • LEFT JOIN
                                  • RIGHT OUTER JOIN
                                  • RIGHT JOIN
                                  • FULL OUTER JOIN
                                  • FULL JOIN
                                  • OFFSET
                                  • LIMIT
                                  • WHERE
                                  Supported functions:
                                  • AVG()
                                  • SUM()
                                  • COUNT()
                                  • MIN()
                                  • MAX()
                                  • REDACTION()
                                  + */ + @JsonProperty("query") + public String getQuery() { + return query; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetQueryRequest && equalTo((GetQueryRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetQueryRequest other) { + return query.equals(other.query); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.query); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static QueryStage builder() { + return new Builder(); + } + + public interface QueryStage { + /** + *

                                  The SQL query to execute.

                                  Supported commands:

                                  • SELECT
                                  Supported operators:
                                  • >
                                  • <
                                  • =
                                  • AND
                                  • OR
                                  • NOT
                                  • LIKE
                                  • ILIKE
                                  • NULL
                                  • NOT NULL
                                  Supported keywords:
                                  • FROM
                                  • JOIN
                                  • INNER JOIN
                                  • LEFT OUTER JOIN
                                  • LEFT JOIN
                                  • RIGHT OUTER JOIN
                                  • RIGHT JOIN
                                  • FULL OUTER JOIN
                                  • FULL JOIN
                                  • OFFSET
                                  • LIMIT
                                  • WHERE
                                  Supported functions:
                                  • AVG()
                                  • SUM()
                                  • COUNT()
                                  • MIN()
                                  • MAX()
                                  • REDACTION()

                                  + */ + _FinalStage query(@NotNull String query); + + Builder from(GetQueryRequest other); + } + + public interface _FinalStage { + GetQueryRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements QueryStage, _FinalStage { + private String query; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(GetQueryRequest other) { + query(other.getQuery()); + return this; + } + + /** + *

                                  The SQL query to execute.

                                  Supported commands:

                                  • SELECT
                                  Supported operators:
                                  • >
                                  • <
                                  • =
                                  • AND
                                  • OR
                                  • NOT
                                  • LIKE
                                  • ILIKE
                                  • NULL
                                  • NOT NULL
                                  Supported keywords:
                                  • FROM
                                  • JOIN
                                  • INNER JOIN
                                  • LEFT OUTER JOIN
                                  • LEFT JOIN
                                  • RIGHT OUTER JOIN
                                  • RIGHT JOIN
                                  • FULL OUTER JOIN
                                  • FULL JOIN
                                  • OFFSET
                                  • LIMIT
                                  • WHERE
                                  Supported functions:
                                  • AVG()
                                  • SUM()
                                  • COUNT()
                                  • MIN()
                                  • MAX()
                                  • REDACTION()

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("query") + public _FinalStage query(@NotNull String query) { + this.query = Objects.requireNonNull(query, "query must not be null"); + return this; + } + + @java.lang.Override + public GetQueryRequest build() { + return new GetQueryRequest(query, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/QueryServiceExecuteQueryBody.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/QueryServiceExecuteQueryBody.java deleted file mode 100644 index 000cd685..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/query/requests/QueryServiceExecuteQueryBody.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.query.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = QueryServiceExecuteQueryBody.Builder.class) -public final class QueryServiceExecuteQueryBody { - private final Optional query; - - private final Map additionalProperties; - - private QueryServiceExecuteQueryBody(Optional query, Map additionalProperties) { - this.query = query; - this.additionalProperties = additionalProperties; - } - - /** - * @return The SQL query to execute.<br><br><b>Supported commands:</b> <ul> <li><code>SELECT</code></li> </ul> <b>Supported operators:</b> <ul> <li><code>></code></li> <li><code><</code></li> <li><code>=</code></li> <li><code>AND</code></li> <li><code>OR</code></li> <li><code>NOT</code></li> <li><code>LIKE</code></li> <li><code>ILIKE</code></li> <li><code>NULL</code></li> <li><code>NOT NULL</code></li> </ul> <b>Supported keywords:</b> <ul> <li><code>FROM</code></li> <li><code>JOIN</code></li> <li><code>INNER JOIN</code></li> <li><code>LEFT OUTER JOIN</code></li> <li><code>LEFT JOIN</code></li> <li><code>RIGHT OUTER JOIN</code></li> <li><code>RIGHT JOIN</code></li> <li><code>FULL OUTER JOIN</code></li> <li><code>FULL JOIN</code></li> <li><code>OFFSET</code></li> <li><code>LIMIT</code></li> <li><code>WHERE</code></li> </ul> <b>Supported functions:</b> <ul> <li><code>AVG()</code></li> <li><code>SUM()</code></li> <li><code>COUNT()</code></li> <li><code>MIN()</code></li> <li><code>MAX()</code></li> <li><code>REDACTION()</code></li> </ul> - */ - @JsonProperty("query") - public Optional getQuery() { - return query; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof QueryServiceExecuteQueryBody && equalTo((QueryServiceExecuteQueryBody) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(QueryServiceExecuteQueryBody other) { - return query.equals(other.query); - } - - @Override - public int hashCode() { - return Objects.hash(this.query); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional query = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(QueryServiceExecuteQueryBody other) { - query(other.getQuery()); - return this; - } - - /** - *

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

                                  - */ - @JsonSetter(value = "query", nulls = Nulls.SKIP) - public Builder query(Optional query) { - this.query = query; - return this; - } - - public Builder query(String query) { - this.query = Optional.ofNullable(query); - return this; - } - - public QueryServiceExecuteQueryBody build() { - return new QueryServiceExecuteQueryBody(query, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java index b1c9ae18..d9cf1510 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java @@ -4,21 +4,46 @@ package com.skyflow.generated.rest.resources.records; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; import com.skyflow.generated.rest.errors.BadRequestError; import com.skyflow.generated.rest.errors.InternalServerError; import com.skyflow.generated.rest.errors.NotFoundError; import com.skyflow.generated.rest.errors.UnauthorizedError; -import com.skyflow.generated.rest.resources.records.requests.*; -import com.skyflow.generated.rest.types.*; -import okhttp3.*; -import org.jetbrains.annotations.NotNull; - -import java.io.File; +import com.skyflow.generated.rest.resources.records.requests.BatchOperationRequest; +import com.skyflow.generated.rest.resources.records.requests.BulkDeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.DeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordByIdRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordsRequest; +import com.skyflow.generated.rest.resources.records.requests.InsertRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.UpdateRecordRequest; +import com.skyflow.generated.rest.types.BatchOperationResponse; +import com.skyflow.generated.rest.types.BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.BulkGetRecordResponse; +import com.skyflow.generated.rest.types.DeleteRecordResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.GetFieldRecords; +import com.skyflow.generated.rest.types.InsertRecordResponse; +import com.skyflow.generated.rest.types.UpdateRecordResponse; import java.io.IOException; -import java.nio.file.Files; -import java.util.Optional; import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; public class AsyncRawRecordsClient { protected final ClientOptions clientOptions; @@ -30,30 +55,25 @@ public AsyncRawRecordsClient(ClientOptions clientOptions) { /** * Performs multiple record operations in a single transaction. */ - public CompletableFuture> recordServiceBatchOperation( - String vaultId) { - return recordServiceBatchOperation( - vaultId, RecordServiceBatchOperationBody.builder().build()); + public CompletableFuture> batchOperation( + String vaultId, BatchOperationRequest request) { + return batchOperation(vaultId, request, null); } /** * Performs multiple record operations in a single transaction. */ - public CompletableFuture> recordServiceBatchOperation( - String vaultId, RecordServiceBatchOperationBody request) { - return recordServiceBatchOperation(vaultId, request, null); - } - - /** - * Performs multiple record operations in a single transaction. - */ - public CompletableFuture> recordServiceBatchOperation( - String vaultId, RecordServiceBatchOperationBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> batchOperation( + String vaultId, BatchOperationRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") - .addPathSegment(vaultId) - .build(); + .addPathSegment(vaultId); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -62,7 +82,7 @@ public CompletableFuture> record throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -72,34 +92,60 @@ public CompletableFuture> record if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1BatchOperationResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BatchOperationResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } @@ -114,30 +160,34 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public CompletableFuture> recordServiceBulkGetRecord( + public CompletableFuture> getRecords( String vaultId, String objectName) { - return recordServiceBulkGetRecord( - vaultId, objectName, RecordServiceBulkGetRecordRequest.builder().build()); + return getRecords(vaultId, objectName, GetRecordsRequest.builder().build()); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public CompletableFuture> recordServiceBulkGetRecord( - String vaultId, String objectName, RecordServiceBulkGetRecordRequest request) { - return recordServiceBulkGetRecord(vaultId, objectName, request, null); + public CompletableFuture> getRecords( + String vaultId, String objectName, RequestOptions requestOptions) { + return getRecords(vaultId, objectName, GetRecordsRequest.builder().build(), requestOptions); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public CompletableFuture> recordServiceBulkGetRecord( - String vaultId, - String objectName, - RecordServiceBulkGetRecordRequest request, - RequestOptions requestOptions) { + public CompletableFuture> getRecords( + String vaultId, String objectName, GetRecordsRequest request) { + return getRecords(vaultId, objectName, request, null); + } + + /** + * Returns the specified records from a table. + */ + public CompletableFuture> getRecords( + String vaultId, String objectName, GetRecordsRequest request, RequestOptions requestOptions) { HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") @@ -171,6 +221,13 @@ public CompletableFuture> recordS QueryStringMapper.addQueryParameter( httpUrl, "order_by", request.getOrderBy().get(), false); } + if (request.getReturnFileMetadata().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "returnFileMetadata", + request.getReturnFileMetadata().get(), + false); + } if (request.getSkyflowIds().isPresent()) { QueryStringMapper.addQueryParameter( httpUrl, "skyflow_ids", request.getSkyflowIds().get(), true); @@ -183,6 +240,11 @@ public CompletableFuture> recordS QueryStringMapper.addQueryParameter( httpUrl, "column_values", request.getColumnValues().get(), true); } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } Request.Builder _requestBuilder = new Request.Builder() .url(httpUrl.build()) .method("GET", null) @@ -193,34 +255,60 @@ public CompletableFuture> recordS if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1BulkGetRecordResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BulkGetRecordResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } @@ -235,33 +323,28 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Inserts a record in the specified table.The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. */ - public CompletableFuture> recordServiceInsertRecord( - String vaultId, String objectName) { - return recordServiceInsertRecord( - vaultId, objectName, RecordServiceInsertRecordBody.builder().build()); + public CompletableFuture> insertRecords( + String vaultId, String objectName, InsertRecordRequest request) { + return insertRecords(vaultId, objectName, request, null); } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Inserts a record in the specified table.The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. */ - public CompletableFuture> recordServiceInsertRecord( - String vaultId, String objectName, RecordServiceInsertRecordBody request) { - return recordServiceInsertRecord(vaultId, objectName, request, null); - } - - /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. - */ - public CompletableFuture> recordServiceInsertRecord( - String vaultId, String objectName, RecordServiceInsertRecordBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> insertRecords( + String vaultId, String objectName, InsertRecordRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegment(objectName) - .build(); + .addPathSegment(objectName); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -270,7 +353,7 @@ public CompletableFuture> recordSe throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -280,34 +363,55 @@ public CompletableFuture> recordSe if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1InsertRecordResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, InsertRecordResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } @@ -324,34 +428,44 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { /** * Deletes the specified records from a table. */ - public CompletableFuture> recordServiceBulkDeleteRecord( + public CompletableFuture> deleteRecords( String vaultId, String objectName) { - return recordServiceBulkDeleteRecord( - vaultId, objectName, RecordServiceBulkDeleteRecordBody.builder().build()); + return deleteRecords( + vaultId, objectName, BulkDeleteRecordRequest.builder().build()); } /** * Deletes the specified records from a table. */ - public CompletableFuture> recordServiceBulkDeleteRecord( - String vaultId, String objectName, RecordServiceBulkDeleteRecordBody request) { - return recordServiceBulkDeleteRecord(vaultId, objectName, request, null); + public CompletableFuture> deleteRecords( + String vaultId, String objectName, RequestOptions requestOptions) { + return deleteRecords( + vaultId, objectName, BulkDeleteRecordRequest.builder().build(), requestOptions); } /** * Deletes the specified records from a table. */ - public CompletableFuture> recordServiceBulkDeleteRecord( - String vaultId, - String objectName, - RecordServiceBulkDeleteRecordBody request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> deleteRecords( + String vaultId, String objectName, BulkDeleteRecordRequest request) { + return deleteRecords(vaultId, objectName, request, null); + } + + /** + * Deletes the specified records from a table. + */ + public CompletableFuture> deleteRecords( + String vaultId, String objectName, BulkDeleteRecordRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegment(objectName) - .build(); + .addPathSegment(objectName); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -360,7 +474,7 @@ public CompletableFuture> reco throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("DELETE", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -370,34 +484,60 @@ public CompletableFuture> reco if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1BulkDeleteRecordResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BulkDeleteRecordResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } @@ -414,29 +554,34 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { /** * Returns the specified record from a table. */ - public CompletableFuture> recordServiceGetRecord( + public CompletableFuture> getRecordById( String vaultId, String objectName, String id) { - return recordServiceGetRecord( - vaultId, objectName, id, RecordServiceGetRecordRequest.builder().build()); + return getRecordById( + vaultId, objectName, id, GetRecordByIdRequest.builder().build()); } /** * Returns the specified record from a table. */ - public CompletableFuture> recordServiceGetRecord( - String vaultId, String objectName, String id, RecordServiceGetRecordRequest request) { - return recordServiceGetRecord(vaultId, objectName, id, request, null); + public CompletableFuture> getRecordById( + String vaultId, String objectName, String id, RequestOptions requestOptions) { + return getRecordById( + vaultId, objectName, id, GetRecordByIdRequest.builder().build(), requestOptions); } /** * Returns the specified record from a table. */ - public CompletableFuture> recordServiceGetRecord( - String vaultId, - String objectName, - String id, - RecordServiceGetRecordRequest request, - RequestOptions requestOptions) { + public CompletableFuture> getRecordById( + String vaultId, String objectName, String id, GetRecordByIdRequest request) { + return getRecordById(vaultId, objectName, id, request, null); + } + + /** + * Returns the specified record from a table. + */ + public CompletableFuture> getRecordById( + String vaultId, String objectName, String id, GetRecordByIdRequest request, RequestOptions requestOptions) { HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") @@ -455,10 +600,22 @@ public CompletableFuture> recordServiceGet QueryStringMapper.addQueryParameter( httpUrl, "downloadURL", request.getDownloadUrl().get(), false); } + if (request.getReturnFileMetadata().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "returnFileMetadata", + request.getReturnFileMetadata().get(), + false); + } if (request.getFields().isPresent()) { QueryStringMapper.addQueryParameter( httpUrl, "fields", request.getFields().get(), true); } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } Request.Builder _requestBuilder = new Request.Builder() .url(httpUrl.build()) .method("GET", null) @@ -469,33 +626,60 @@ public CompletableFuture> recordServiceGet if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1FieldRecords.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetFieldRecords.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } @@ -510,38 +694,47 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { } /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public CompletableFuture> recordServiceUpdateRecord( + public CompletableFuture> updateRecord( String vaultId, String objectName, String id) { - return recordServiceUpdateRecord( - vaultId, objectName, id, RecordServiceUpdateRecordBody.builder().build()); + return updateRecord( + vaultId, objectName, id, UpdateRecordRequest.builder().build()); } /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public CompletableFuture> recordServiceUpdateRecord( - String vaultId, String objectName, String id, RecordServiceUpdateRecordBody request) { - return recordServiceUpdateRecord(vaultId, objectName, id, request, null); + public CompletableFuture> updateRecord( + String vaultId, String objectName, String id, RequestOptions requestOptions) { + return updateRecord( + vaultId, objectName, id, UpdateRecordRequest.builder().build(), requestOptions); + } + + /** + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public CompletableFuture> updateRecord( + String vaultId, String objectName, String id, UpdateRecordRequest request) { + return updateRecord(vaultId, objectName, id, request, null); } /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public CompletableFuture> recordServiceUpdateRecord( - String vaultId, - String objectName, - String id, - RecordServiceUpdateRecordBody request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> updateRecord( + String vaultId, String objectName, String id, UpdateRecordRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) .addPathSegment(objectName) - .addPathSegment(id) - .build(); + .addPathSegment(id); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -550,7 +743,7 @@ public CompletableFuture> recordSe throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("PUT", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -560,34 +753,60 @@ public CompletableFuture> recordSe if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1UpdateRecordResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, UpdateRecordResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } @@ -602,133 +821,50 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { } /** - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public CompletableFuture> recordServiceDeleteRecord( + public CompletableFuture> deleteRecord( String vaultId, String objectName, String id) { - return recordServiceDeleteRecord(vaultId, objectName, id, null); + return deleteRecord( + vaultId, objectName, id, DeleteRecordRequest.builder().build()); } /** - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public CompletableFuture> recordServiceDeleteRecord( + public CompletableFuture> deleteRecord( String vaultId, String objectName, String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/vaults") - .addPathSegment(vaultId) - .addPathSegment(objectName) - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1DeleteRecordResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; + return deleteRecord( + vaultId, objectName, id, DeleteRecordRequest.builder().build(), requestOptions); } /** - * Uploads a file to the specified record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public CompletableFuture> fileServiceUploadFile( - String vaultId, String objectName, String id, Optional file) { - return fileServiceUploadFile( - vaultId, - objectName, - id, - file, - FileServiceUploadFileRequest.builder().build()); + public CompletableFuture> deleteRecord( + String vaultId, String objectName, String id, DeleteRecordRequest request) { + return deleteRecord(vaultId, objectName, id, request, null); } /** - * Uploads a file to the specified record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public CompletableFuture> fileServiceUploadFile( - String vaultId, String objectName, String id, Optional file, FileServiceUploadFileRequest request) { - return fileServiceUploadFile(vaultId, objectName, id, file, request, null); - } - - /** - * Uploads a file to the specified record. - */ - public CompletableFuture> fileServiceUploadFile( - String vaultId, - String objectName, - String id, - Optional file, - FileServiceUploadFileRequest request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> deleteRecord( + String vaultId, String objectName, String id, DeleteRecordRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) .addPathSegment(objectName) - .addPathSegment(id) - .addPathSegments("files") - .build(); - MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); - try { - if (file.isPresent()) { - String fileMimeType = Files.probeContentType(file.get().toPath()); - MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; - body.addFormDataPart( - "file", file.get().getName(), RequestBody.create(file.get(), fileMimeTypeMediaType)); - } - if (request.getColumnName().isPresent()) { - QueryStringMapper.addFormDataPart( - body, "columnName", request.getColumnName().get(), false); - } - } catch (Exception e) { - throw new RuntimeException(e); + .addPathSegment(id); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); } Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", body.build()) + .url(httpUrl.build()) + .method("DELETE", null) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Accept", "application/json"); Request okhttpRequest = _requestBuilder.build(); @@ -736,270 +872,42 @@ public CompletableFuture> fileServ if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1UpdateRecordResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Deletes a file from the specified record. - */ - public CompletableFuture> fileServiceDeleteFile( - String vaultId, String tableName, String id, String columnName) { - return fileServiceDeleteFile(vaultId, tableName, id, columnName, null); - } - - /** - * Deletes a file from the specified record. - */ - public CompletableFuture> fileServiceDeleteFile( - String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/vaults") - .addPathSegment(vaultId) - .addPathSegment(tableName) - .addPathSegment(id) - .addPathSegments("files") - .addPathSegment(columnName) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DeleteFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Returns the anti-virus scan status of a file. - */ - public CompletableFuture> fileServiceGetFileScanStatus( - String vaultId, String tableName, String id, String columnName) { - return fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, null); - } - - /** - * Returns the anti-virus scan status of a file. - */ - public CompletableFuture> fileServiceGetFileScanStatus( - String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/vaults") - .addPathSegment(vaultId) - .addPathSegment(tableName) - .addPathSegment(id) - .addPathSegments("files") - .addPathSegment(columnName) - .addPathSegments("scan-status") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); } - CompletableFuture> future = new CompletableFuture<>(); + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1GetFileScanStatusResponse.class), - response)); - return; - } String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. - */ - public CompletableFuture> uploadFileV2( - String vaultId, File file, UploadFileV2Request request) { - return uploadFileV2(vaultId, file, request, null); - } - - /** - * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. - */ - public CompletableFuture> uploadFileV2( - String vaultId, File file, UploadFileV2Request request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/vaults") - .addPathSegment(vaultId) - .addPathSegments("files/upload") - .build(); - MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); - try { - QueryStringMapper.addFormDataPart(body, "tableName", request.getTableName(), false); - QueryStringMapper.addFormDataPart(body, "columnName", request.getColumnName(), false); - String fileMimeType = Files.probeContentType(file.toPath()); - MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; - body.addFormDataPart("file", file.getName(), RequestBody.create(file, fileMimeTypeMediaType)); - if (request.getSkyflowId().isPresent()) { - QueryStringMapper.addFormDataPart( - body, "skyflowID", request.getSkyflowId().get(), false); - } - if (request.getReturnFileMetadata().isPresent()) { - QueryStringMapper.addFormDataPart( - body, - "returnFileMetadata", - request.getReturnFileMetadata().get(), - false); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", body.build()) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UploadFileV2Response.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteRecordResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 401: future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 404: future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response)); return; case 500: @@ -1011,12 +919,13 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java index ed7240c9..43a63d26 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java @@ -5,11 +5,20 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.records.requests.*; -import com.skyflow.generated.rest.types.*; - -import java.io.File; -import java.util.Optional; +import com.skyflow.generated.rest.resources.records.requests.BatchOperationRequest; +import com.skyflow.generated.rest.resources.records.requests.BulkDeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.DeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordByIdRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordsRequest; +import com.skyflow.generated.rest.resources.records.requests.InsertRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.UpdateRecordRequest; +import com.skyflow.generated.rest.types.BatchOperationResponse; +import com.skyflow.generated.rest.types.BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.BulkGetRecordResponse; +import com.skyflow.generated.rest.types.DeleteRecordResponse; +import com.skyflow.generated.rest.types.GetFieldRecords; +import com.skyflow.generated.rest.types.InsertRecordResponse; +import com.skyflow.generated.rest.types.UpdateRecordResponse; import java.util.concurrent.CompletableFuture; public class AsyncRecordsClient { @@ -32,287 +41,204 @@ public AsyncRawRecordsClient withRawResponse() { /** * Performs multiple record operations in a single transaction. */ - public CompletableFuture recordServiceBatchOperation(String vaultId) { - return this.rawClient.recordServiceBatchOperation(vaultId).thenApply(response -> response.body()); + public CompletableFuture batchOperation(String vaultId, BatchOperationRequest request) { + return this.rawClient.batchOperation(vaultId, request).thenApply(response -> response.body()); } /** * Performs multiple record operations in a single transaction. */ - public CompletableFuture recordServiceBatchOperation( - String vaultId, RecordServiceBatchOperationBody request) { - return this.rawClient.recordServiceBatchOperation(vaultId, request).thenApply(response -> response.body()); + public CompletableFuture batchOperation( + String vaultId, BatchOperationRequest request, RequestOptions requestOptions) { + return this.rawClient.batchOperation(vaultId, request, requestOptions).thenApply(response -> response.body()); } /** - * Performs multiple record operations in a single transaction. + * Returns the specified records from a table. */ - public CompletableFuture recordServiceBatchOperation( - String vaultId, RecordServiceBatchOperationBody request, RequestOptions requestOptions) { - return this.rawClient - .recordServiceBatchOperation(vaultId, request, requestOptions) - .thenApply(response -> response.body()); + public CompletableFuture getRecords(String vaultId, String objectName) { + return this.rawClient.getRecords(vaultId, objectName).thenApply(response -> response.body()); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public CompletableFuture recordServiceBulkGetRecord(String vaultId, String objectName) { - return this.rawClient.recordServiceBulkGetRecord(vaultId, objectName).thenApply(response -> response.body()); + public CompletableFuture getRecords( + String vaultId, String objectName, RequestOptions requestOptions) { + return this.rawClient.getRecords(vaultId, objectName, requestOptions).thenApply(response -> response.body()); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public CompletableFuture recordServiceBulkGetRecord( - String vaultId, String objectName, RecordServiceBulkGetRecordRequest request) { - return this.rawClient - .recordServiceBulkGetRecord(vaultId, objectName, request) - .thenApply(response -> response.body()); + public CompletableFuture getRecords( + String vaultId, String objectName, GetRecordsRequest request) { + return this.rawClient.getRecords(vaultId, objectName, request).thenApply(response -> response.body()); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public CompletableFuture recordServiceBulkGetRecord( - String vaultId, - String objectName, - RecordServiceBulkGetRecordRequest request, - RequestOptions requestOptions) { + public CompletableFuture getRecords( + String vaultId, String objectName, GetRecordsRequest request, RequestOptions requestOptions) { return this.rawClient - .recordServiceBulkGetRecord(vaultId, objectName, request, requestOptions) + .getRecords(vaultId, objectName, request, requestOptions) .thenApply(response -> response.body()); } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Inserts a record in the specified table.The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. */ - public CompletableFuture recordServiceInsertRecord(String vaultId, String objectName) { - return this.rawClient.recordServiceInsertRecord(vaultId, objectName).thenApply(response -> response.body()); + public CompletableFuture insertRecords( + String vaultId, String objectName, InsertRecordRequest request) { + return this.rawClient.insertRecords(vaultId, objectName, request).thenApply(response -> response.body()); } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Inserts a record in the specified table.The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. */ - public CompletableFuture recordServiceInsertRecord( - String vaultId, String objectName, RecordServiceInsertRecordBody request) { + public CompletableFuture insertRecords( + String vaultId, String objectName, InsertRecordRequest request, RequestOptions requestOptions) { return this.rawClient - .recordServiceInsertRecord(vaultId, objectName, request) + .insertRecords(vaultId, objectName, request, requestOptions) .thenApply(response -> response.body()); } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Deletes the specified records from a table. */ - public CompletableFuture recordServiceInsertRecord( - String vaultId, String objectName, RecordServiceInsertRecordBody request, RequestOptions requestOptions) { - return this.rawClient - .recordServiceInsertRecord(vaultId, objectName, request, requestOptions) - .thenApply(response -> response.body()); + public CompletableFuture deleteRecords(String vaultId, String objectName) { + return this.rawClient.deleteRecords(vaultId, objectName).thenApply(response -> response.body()); } /** * Deletes the specified records from a table. */ - public CompletableFuture recordServiceBulkDeleteRecord( - String vaultId, String objectName) { - return this.rawClient.recordServiceBulkDeleteRecord(vaultId, objectName).thenApply(response -> response.body()); + public CompletableFuture deleteRecords( + String vaultId, String objectName, RequestOptions requestOptions) { + return this.rawClient.deleteRecords(vaultId, objectName, requestOptions).thenApply(response -> response.body()); } /** * Deletes the specified records from a table. */ - public CompletableFuture recordServiceBulkDeleteRecord( - String vaultId, String objectName, RecordServiceBulkDeleteRecordBody request) { - return this.rawClient - .recordServiceBulkDeleteRecord(vaultId, objectName, request) - .thenApply(response -> response.body()); + public CompletableFuture deleteRecords( + String vaultId, String objectName, BulkDeleteRecordRequest request) { + return this.rawClient.deleteRecords(vaultId, objectName, request).thenApply(response -> response.body()); } /** * Deletes the specified records from a table. */ - public CompletableFuture recordServiceBulkDeleteRecord( - String vaultId, - String objectName, - RecordServiceBulkDeleteRecordBody request, - RequestOptions requestOptions) { + public CompletableFuture deleteRecords( + String vaultId, String objectName, BulkDeleteRecordRequest request, RequestOptions requestOptions) { return this.rawClient - .recordServiceBulkDeleteRecord(vaultId, objectName, request, requestOptions) + .deleteRecords(vaultId, objectName, request, requestOptions) .thenApply(response -> response.body()); } /** * Returns the specified record from a table. */ - public CompletableFuture recordServiceGetRecord(String vaultId, String objectName, String id) { - return this.rawClient.recordServiceGetRecord(vaultId, objectName, id).thenApply(response -> response.body()); + public CompletableFuture getRecordById(String vaultId, String objectName, String id) { + return this.rawClient.getRecordById(vaultId, objectName, id).thenApply(response -> response.body()); } /** * Returns the specified record from a table. */ - public CompletableFuture recordServiceGetRecord( - String vaultId, String objectName, String id, RecordServiceGetRecordRequest request) { + public CompletableFuture getRecordById( + String vaultId, String objectName, String id, RequestOptions requestOptions) { return this.rawClient - .recordServiceGetRecord(vaultId, objectName, id, request) + .getRecordById(vaultId, objectName, id, requestOptions) .thenApply(response -> response.body()); } /** * Returns the specified record from a table. */ - public CompletableFuture recordServiceGetRecord( - String vaultId, - String objectName, - String id, - RecordServiceGetRecordRequest request, - RequestOptions requestOptions) { - return this.rawClient - .recordServiceGetRecord(vaultId, objectName, id, request, requestOptions) - .thenApply(response -> response.body()); - } - - /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. - */ - public CompletableFuture recordServiceUpdateRecord( - String vaultId, String objectName, String id) { - return this.rawClient.recordServiceUpdateRecord(vaultId, objectName, id).thenApply(response -> response.body()); - } - - /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. - */ - public CompletableFuture recordServiceUpdateRecord( - String vaultId, String objectName, String id, RecordServiceUpdateRecordBody request) { - return this.rawClient - .recordServiceUpdateRecord(vaultId, objectName, id, request) - .thenApply(response -> response.body()); + public CompletableFuture getRecordById( + String vaultId, String objectName, String id, GetRecordByIdRequest request) { + return this.rawClient.getRecordById(vaultId, objectName, id, request).thenApply(response -> response.body()); } /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * Returns the specified record from a table. */ - public CompletableFuture recordServiceUpdateRecord( - String vaultId, - String objectName, - String id, - RecordServiceUpdateRecordBody request, - RequestOptions requestOptions) { + public CompletableFuture getRecordById( + String vaultId, String objectName, String id, GetRecordByIdRequest request, RequestOptions requestOptions) { return this.rawClient - .recordServiceUpdateRecord(vaultId, objectName, id, request, requestOptions) + .getRecordById(vaultId, objectName, id, request, requestOptions) .thenApply(response -> response.body()); } /** - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public CompletableFuture recordServiceDeleteRecord( - String vaultId, String objectName, String id) { - return this.rawClient.recordServiceDeleteRecord(vaultId, objectName, id).thenApply(response -> response.body()); + public CompletableFuture updateRecord(String vaultId, String objectName, String id) { + return this.rawClient.updateRecord(vaultId, objectName, id).thenApply(response -> response.body()); } /** - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public CompletableFuture recordServiceDeleteRecord( + public CompletableFuture updateRecord( String vaultId, String objectName, String id, RequestOptions requestOptions) { return this.rawClient - .recordServiceDeleteRecord(vaultId, objectName, id, requestOptions) - .thenApply(response -> response.body()); - } - - /** - * Uploads a file to the specified record. - */ - public CompletableFuture fileServiceUploadFile( - String vaultId, String objectName, String id, Optional file) { - return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, file) - .thenApply(response -> response.body()); - } - - /** - * Uploads a file to the specified record. - */ - public CompletableFuture fileServiceUploadFile( - String vaultId, String objectName, String id, Optional file, FileServiceUploadFileRequest request) { - return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, file, request) - .thenApply(response -> response.body()); - } - - /** - * Uploads a file to the specified record. - */ - public CompletableFuture fileServiceUploadFile( - String vaultId, - String objectName, - String id, - Optional file, - FileServiceUploadFileRequest request, - RequestOptions requestOptions) { - return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, file, request, requestOptions) + .updateRecord(vaultId, objectName, id, requestOptions) .thenApply(response -> response.body()); } /** - * Deletes a file from the specified record. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public CompletableFuture fileServiceDeleteFile( - String vaultId, String tableName, String id, String columnName) { - return this.rawClient - .fileServiceDeleteFile(vaultId, tableName, id, columnName) - .thenApply(response -> response.body()); + public CompletableFuture updateRecord( + String vaultId, String objectName, String id, UpdateRecordRequest request) { + return this.rawClient.updateRecord(vaultId, objectName, id, request).thenApply(response -> response.body()); } /** - * Deletes a file from the specified record. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public CompletableFuture fileServiceDeleteFile( - String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + public CompletableFuture updateRecord( + String vaultId, String objectName, String id, UpdateRecordRequest request, RequestOptions requestOptions) { return this.rawClient - .fileServiceDeleteFile(vaultId, tableName, id, columnName, requestOptions) + .updateRecord(vaultId, objectName, id, request, requestOptions) .thenApply(response -> response.body()); } /** - * Returns the anti-virus scan status of a file. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public CompletableFuture fileServiceGetFileScanStatus( - String vaultId, String tableName, String id, String columnName) { - return this.rawClient - .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName) - .thenApply(response -> response.body()); + public CompletableFuture deleteRecord(String vaultId, String objectName, String id) { + return this.rawClient.deleteRecord(vaultId, objectName, id).thenApply(response -> response.body()); } /** - * Returns the anti-virus scan status of a file. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public CompletableFuture fileServiceGetFileScanStatus( - String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + public CompletableFuture deleteRecord( + String vaultId, String objectName, String id, RequestOptions requestOptions) { return this.rawClient - .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, requestOptions) + .deleteRecord(vaultId, objectName, id, requestOptions) .thenApply(response -> response.body()); } /** - * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public CompletableFuture uploadFileV2( - String vaultId, File file, UploadFileV2Request request) { - return this.rawClient.uploadFileV2(vaultId, file, request).thenApply(response -> response.body()); + public CompletableFuture deleteRecord( + String vaultId, String objectName, String id, DeleteRecordRequest request) { + return this.rawClient.deleteRecord(vaultId, objectName, id, request).thenApply(response -> response.body()); } /** - * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public CompletableFuture uploadFileV2( - String vaultId, File file, UploadFileV2Request request, RequestOptions requestOptions) { + public CompletableFuture deleteRecord( + String vaultId, String objectName, String id, DeleteRecordRequest request, RequestOptions requestOptions) { return this.rawClient - .uploadFileV2(vaultId, file, request, requestOptions) + .deleteRecord(vaultId, objectName, id, request, requestOptions) .thenApply(response -> response.body()); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java index 29530b56..6b72953f 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java @@ -4,19 +4,42 @@ package com.skyflow.generated.rest.resources.records; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; import com.skyflow.generated.rest.errors.BadRequestError; import com.skyflow.generated.rest.errors.InternalServerError; import com.skyflow.generated.rest.errors.NotFoundError; import com.skyflow.generated.rest.errors.UnauthorizedError; -import com.skyflow.generated.rest.resources.records.requests.*; -import com.skyflow.generated.rest.types.*; -import okhttp3.*; - -import java.io.File; +import com.skyflow.generated.rest.resources.records.requests.BatchOperationRequest; +import com.skyflow.generated.rest.resources.records.requests.BulkDeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.DeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordByIdRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordsRequest; +import com.skyflow.generated.rest.resources.records.requests.InsertRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.UpdateRecordRequest; +import com.skyflow.generated.rest.types.BatchOperationResponse; +import com.skyflow.generated.rest.types.BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.BulkGetRecordResponse; +import com.skyflow.generated.rest.types.DeleteRecordResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.GetFieldRecords; +import com.skyflow.generated.rest.types.InsertRecordResponse; +import com.skyflow.generated.rest.types.UpdateRecordResponse; import java.io.IOException; -import java.nio.file.Files; -import java.util.Optional; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class RawRecordsClient { protected final ClientOptions clientOptions; @@ -28,29 +51,24 @@ public RawRecordsClient(ClientOptions clientOptions) { /** * Performs multiple record operations in a single transaction. */ - public ApiClientHttpResponse recordServiceBatchOperation(String vaultId) { - return recordServiceBatchOperation( - vaultId, RecordServiceBatchOperationBody.builder().build()); - } - - /** - * Performs multiple record operations in a single transaction. - */ - public ApiClientHttpResponse recordServiceBatchOperation( - String vaultId, RecordServiceBatchOperationBody request) { - return recordServiceBatchOperation(vaultId, request, null); + public ApiClientHttpResponse batchOperation(String vaultId, BatchOperationRequest request) { + return batchOperation(vaultId, request, null); } /** * Performs multiple record operations in a single transaction. */ - public ApiClientHttpResponse recordServiceBatchOperation( - String vaultId, RecordServiceBatchOperationBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse batchOperation( + String vaultId, BatchOperationRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") - .addPathSegment(vaultId) - .build(); + .addPathSegment(vaultId); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -59,7 +77,7 @@ public ApiClientHttpResponse recordServiceBatchOperati throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -69,57 +87,79 @@ public ApiClientHttpResponse recordServiceBatchOperati if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BatchOperationResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BatchOperationResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } } /** - * Gets the specified records from a table. + * Returns the specified records from a table. + */ + public ApiClientHttpResponse getRecords(String vaultId, String objectName) { + return getRecords(vaultId, objectName, GetRecordsRequest.builder().build()); + } + + /** + * Returns the specified records from a table. */ - public ApiClientHttpResponse recordServiceBulkGetRecord( - String vaultId, String objectName) { - return recordServiceBulkGetRecord( - vaultId, objectName, RecordServiceBulkGetRecordRequest.builder().build()); + public ApiClientHttpResponse getRecords( + String vaultId, String objectName, RequestOptions requestOptions) { + return getRecords(vaultId, objectName, GetRecordsRequest.builder().build(), requestOptions); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public ApiClientHttpResponse recordServiceBulkGetRecord( - String vaultId, String objectName, RecordServiceBulkGetRecordRequest request) { - return recordServiceBulkGetRecord(vaultId, objectName, request, null); + public ApiClientHttpResponse getRecords( + String vaultId, String objectName, GetRecordsRequest request) { + return getRecords(vaultId, objectName, request, null); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public ApiClientHttpResponse recordServiceBulkGetRecord( - String vaultId, - String objectName, - RecordServiceBulkGetRecordRequest request, - RequestOptions requestOptions) { + public ApiClientHttpResponse getRecords( + String vaultId, String objectName, GetRecordsRequest request, RequestOptions requestOptions) { HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") @@ -153,6 +193,13 @@ public ApiClientHttpResponse recordServiceBulkGetRecord QueryStringMapper.addQueryParameter( httpUrl, "order_by", request.getOrderBy().get(), false); } + if (request.getReturnFileMetadata().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "returnFileMetadata", + request.getReturnFileMetadata().get(), + false); + } if (request.getSkyflowIds().isPresent()) { QueryStringMapper.addQueryParameter( httpUrl, "skyflow_ids", request.getSkyflowIds().get(), true); @@ -165,6 +212,11 @@ public ApiClientHttpResponse recordServiceBulkGetRecord QueryStringMapper.addQueryParameter( httpUrl, "column_values", request.getColumnValues().get(), true); } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } Request.Builder _requestBuilder = new Request.Builder() .url(httpUrl.build()) .method("GET", null) @@ -175,59 +227,73 @@ public ApiClientHttpResponse recordServiceBulkGetRecord if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BulkGetRecordResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BulkGetRecordResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. - */ - public ApiClientHttpResponse recordServiceInsertRecord(String vaultId, String objectName) { - return recordServiceInsertRecord( - vaultId, objectName, RecordServiceInsertRecordBody.builder().build()); - } - - /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Inserts a record in the specified table.The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. */ - public ApiClientHttpResponse recordServiceInsertRecord( - String vaultId, String objectName, RecordServiceInsertRecordBody request) { - return recordServiceInsertRecord(vaultId, objectName, request, null); + public ApiClientHttpResponse insertRecords( + String vaultId, String objectName, InsertRecordRequest request) { + return insertRecords(vaultId, objectName, request, null); } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Inserts a record in the specified table.The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. */ - public ApiClientHttpResponse recordServiceInsertRecord( - String vaultId, String objectName, RecordServiceInsertRecordBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse insertRecords( + String vaultId, String objectName, InsertRecordRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegment(objectName) - .build(); + .addPathSegment(objectName); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -236,7 +302,7 @@ public ApiClientHttpResponse recordServiceInsertRecord( throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -246,27 +312,42 @@ public ApiClientHttpResponse recordServiceInsertRecord( if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1InsertRecordResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, InsertRecordResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } @@ -275,34 +356,43 @@ public ApiClientHttpResponse recordServiceInsertRecord( /** * Deletes the specified records from a table. */ - public ApiClientHttpResponse recordServiceBulkDeleteRecord( - String vaultId, String objectName) { - return recordServiceBulkDeleteRecord( - vaultId, objectName, RecordServiceBulkDeleteRecordBody.builder().build()); + public ApiClientHttpResponse deleteRecords(String vaultId, String objectName) { + return deleteRecords( + vaultId, objectName, BulkDeleteRecordRequest.builder().build()); + } + + /** + * Deletes the specified records from a table. + */ + public ApiClientHttpResponse deleteRecords( + String vaultId, String objectName, RequestOptions requestOptions) { + return deleteRecords( + vaultId, objectName, BulkDeleteRecordRequest.builder().build(), requestOptions); } /** * Deletes the specified records from a table. */ - public ApiClientHttpResponse recordServiceBulkDeleteRecord( - String vaultId, String objectName, RecordServiceBulkDeleteRecordBody request) { - return recordServiceBulkDeleteRecord(vaultId, objectName, request, null); + public ApiClientHttpResponse deleteRecords( + String vaultId, String objectName, BulkDeleteRecordRequest request) { + return deleteRecords(vaultId, objectName, request, null); } /** * Deletes the specified records from a table. */ - public ApiClientHttpResponse recordServiceBulkDeleteRecord( - String vaultId, - String objectName, - RecordServiceBulkDeleteRecordBody request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse deleteRecords( + String vaultId, String objectName, BulkDeleteRecordRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegment(objectName) - .build(); + .addPathSegment(objectName); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -311,7 +401,7 @@ public ApiClientHttpResponse recordServiceBulkDelete throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("DELETE", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -321,27 +411,46 @@ public ApiClientHttpResponse recordServiceBulkDelete if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BulkDeleteRecordResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BulkDeleteRecordResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } @@ -350,28 +459,33 @@ public ApiClientHttpResponse recordServiceBulkDelete /** * Returns the specified record from a table. */ - public ApiClientHttpResponse recordServiceGetRecord(String vaultId, String objectName, String id) { - return recordServiceGetRecord( - vaultId, objectName, id, RecordServiceGetRecordRequest.builder().build()); + public ApiClientHttpResponse getRecordById(String vaultId, String objectName, String id) { + return getRecordById( + vaultId, objectName, id, GetRecordByIdRequest.builder().build()); + } + + /** + * Returns the specified record from a table. + */ + public ApiClientHttpResponse getRecordById( + String vaultId, String objectName, String id, RequestOptions requestOptions) { + return getRecordById( + vaultId, objectName, id, GetRecordByIdRequest.builder().build(), requestOptions); } /** * Returns the specified record from a table. */ - public ApiClientHttpResponse recordServiceGetRecord( - String vaultId, String objectName, String id, RecordServiceGetRecordRequest request) { - return recordServiceGetRecord(vaultId, objectName, id, request, null); + public ApiClientHttpResponse getRecordById( + String vaultId, String objectName, String id, GetRecordByIdRequest request) { + return getRecordById(vaultId, objectName, id, request, null); } /** * Returns the specified record from a table. */ - public ApiClientHttpResponse recordServiceGetRecord( - String vaultId, - String objectName, - String id, - RecordServiceGetRecordRequest request, - RequestOptions requestOptions) { + public ApiClientHttpResponse getRecordById( + String vaultId, String objectName, String id, GetRecordByIdRequest request, RequestOptions requestOptions) { HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") @@ -390,10 +504,22 @@ public ApiClientHttpResponse recordServiceGetRecord( QueryStringMapper.addQueryParameter( httpUrl, "downloadURL", request.getDownloadUrl().get(), false); } + if (request.getReturnFileMetadata().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "returnFileMetadata", + request.getReturnFileMetadata().get(), + false); + } if (request.getFields().isPresent()) { QueryStringMapper.addQueryParameter( httpUrl, "fields", request.getFields().get(), true); } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } Request.Builder _requestBuilder = new Request.Builder() .url(httpUrl.build()) .method("GET", null) @@ -404,64 +530,91 @@ public ApiClientHttpResponse recordServiceGetRecord( if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1FieldRecords.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetFieldRecords.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } } /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public ApiClientHttpResponse updateRecord(String vaultId, String objectName, String id) { + return updateRecord( + vaultId, objectName, id, UpdateRecordRequest.builder().build()); + } + + /** + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public ApiClientHttpResponse recordServiceUpdateRecord( - String vaultId, String objectName, String id) { - return recordServiceUpdateRecord( - vaultId, objectName, id, RecordServiceUpdateRecordBody.builder().build()); + public ApiClientHttpResponse updateRecord( + String vaultId, String objectName, String id, RequestOptions requestOptions) { + return updateRecord( + vaultId, objectName, id, UpdateRecordRequest.builder().build(), requestOptions); } /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public ApiClientHttpResponse recordServiceUpdateRecord( - String vaultId, String objectName, String id, RecordServiceUpdateRecordBody request) { - return recordServiceUpdateRecord(vaultId, objectName, id, request, null); + public ApiClientHttpResponse updateRecord( + String vaultId, String objectName, String id, UpdateRecordRequest request) { + return updateRecord(vaultId, objectName, id, request, null); } /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public ApiClientHttpResponse recordServiceUpdateRecord( - String vaultId, - String objectName, - String id, - RecordServiceUpdateRecordBody request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse updateRecord( + String vaultId, String objectName, String id, UpdateRecordRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) .addPathSegment(objectName) - .addPathSegment(id) - .build(); + .addPathSegment(id); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -470,7 +623,7 @@ public ApiClientHttpResponse recordServiceUpdateRecord( throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("PUT", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -480,145 +633,94 @@ public ApiClientHttpResponse recordServiceUpdateRecord( if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1UpdateRecordResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, UpdateRecordResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } } /** - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public ApiClientHttpResponse recordServiceDeleteRecord( - String vaultId, String objectName, String id) { - return recordServiceDeleteRecord(vaultId, objectName, id, null); + public ApiClientHttpResponse deleteRecord(String vaultId, String objectName, String id) { + return deleteRecord( + vaultId, objectName, id, DeleteRecordRequest.builder().build()); } /** - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public ApiClientHttpResponse recordServiceDeleteRecord( + public ApiClientHttpResponse deleteRecord( String vaultId, String objectName, String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/vaults") - .addPathSegment(vaultId) - .addPathSegment(objectName) - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DeleteRecordResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } + return deleteRecord( + vaultId, objectName, id, DeleteRecordRequest.builder().build(), requestOptions); } /** - * Uploads a file to the specified record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public ApiClientHttpResponse fileServiceUploadFile( - String vaultId, String objectName, String id, Optional file) { - return fileServiceUploadFile( - vaultId, - objectName, - id, - file, - FileServiceUploadFileRequest.builder().build()); + public ApiClientHttpResponse deleteRecord( + String vaultId, String objectName, String id, DeleteRecordRequest request) { + return deleteRecord(vaultId, objectName, id, request, null); } /** - * Uploads a file to the specified record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public ApiClientHttpResponse fileServiceUploadFile( - String vaultId, String objectName, String id, Optional file, FileServiceUploadFileRequest request) { - return fileServiceUploadFile(vaultId, objectName, id, file, request, null); - } - - /** - * Uploads a file to the specified record. - */ - public ApiClientHttpResponse fileServiceUploadFile( - String vaultId, - String objectName, - String id, - Optional file, - FileServiceUploadFileRequest request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse deleteRecord( + String vaultId, String objectName, String id, DeleteRecordRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) .addPathSegment(objectName) - .addPathSegment(id) - .addPathSegments("files") - .build(); - MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); - try { - if (file.isPresent()) { - String fileMimeType = Files.probeContentType(file.get().toPath()); - MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; - body.addFormDataPart( - "file", file.get().getName(), RequestBody.create(file.get(), fileMimeTypeMediaType)); - } - if (request.getColumnName().isPresent()) { - QueryStringMapper.addFormDataPart( - body, "columnName", request.getColumnName().get(), false); - } - } catch (Exception e) { - throw new RuntimeException(e); + .addPathSegment(id); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); } Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", body.build()) + .url(httpUrl.build()) + .method("DELETE", null) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Accept", "application/json"); Request okhttpRequest = _requestBuilder.build(); @@ -626,218 +728,33 @@ public ApiClientHttpResponse fileServiceUploadFile( if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1UpdateRecordResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * Deletes a file from the specified record. - */ - public ApiClientHttpResponse fileServiceDeleteFile( - String vaultId, String tableName, String id, String columnName) { - return fileServiceDeleteFile(vaultId, tableName, id, columnName, null); - } - - /** - * Deletes a file from the specified record. - */ - public ApiClientHttpResponse fileServiceDeleteFile( - String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/vaults") - .addPathSegment(vaultId) - .addPathSegment(tableName) - .addPathSegment(id) - .addPathSegments("files") - .addPathSegment(columnName) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DeleteFileResponse.class), - response); - } String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * Returns the anti-virus scan status of a file. - */ - public ApiClientHttpResponse fileServiceGetFileScanStatus( - String vaultId, String tableName, String id, String columnName) { - return fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, null); - } - - /** - * Returns the anti-virus scan status of a file. - */ - public ApiClientHttpResponse fileServiceGetFileScanStatus( - String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/vaults") - .addPathSegment(vaultId) - .addPathSegment(tableName) - .addPathSegment(id) - .addPathSegments("files") - .addPathSegment(columnName) - .addPathSegments("scan-status") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1GetFileScanStatusResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteRecordResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. - */ - public ApiClientHttpResponse uploadFileV2( - String vaultId, File file, UploadFileV2Request request) { - return uploadFileV2(vaultId, file, request, null); - } - - /** - * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. - */ - public ApiClientHttpResponse uploadFileV2( - String vaultId, File file, UploadFileV2Request request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/vaults") - .addPathSegment(vaultId) - .addPathSegments("files/upload") - .build(); - MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); - try { - QueryStringMapper.addFormDataPart(body, "tableName", request.getTableName(), false); - QueryStringMapper.addFormDataPart(body, "columnName", request.getColumnName(), false); - String fileMimeType = Files.probeContentType(file.toPath()); - MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; - body.addFormDataPart("file", file.getName(), RequestBody.create(file, fileMimeTypeMediaType)); - if (request.getSkyflowId().isPresent()) { - QueryStringMapper.addFormDataPart( - body, "skyflowID", request.getSkyflowId().get(), false); - } - if (request.getReturnFileMetadata().isPresent()) { - QueryStringMapper.addFormDataPart( - body, - "returnFileMetadata", - request.getReturnFileMetadata().get(), - false); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", body.build()) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UploadFileV2Response.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); case 401: throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); case 404: throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); case 500: throw new InternalServerError( ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); @@ -845,11 +762,11 @@ public ApiClientHttpResponse uploadFileV2( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java index eb9bc81d..0a1da515 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java @@ -5,11 +5,20 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.records.requests.*; -import com.skyflow.generated.rest.types.*; - -import java.io.File; -import java.util.Optional; +import com.skyflow.generated.rest.resources.records.requests.BatchOperationRequest; +import com.skyflow.generated.rest.resources.records.requests.BulkDeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.DeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordByIdRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordsRequest; +import com.skyflow.generated.rest.resources.records.requests.InsertRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.UpdateRecordRequest; +import com.skyflow.generated.rest.types.BatchOperationResponse; +import com.skyflow.generated.rest.types.BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.BulkGetRecordResponse; +import com.skyflow.generated.rest.types.DeleteRecordResponse; +import com.skyflow.generated.rest.types.GetFieldRecords; +import com.skyflow.generated.rest.types.InsertRecordResponse; +import com.skyflow.generated.rest.types.UpdateRecordResponse; public class RecordsClient { protected final ClientOptions clientOptions; @@ -31,282 +40,197 @@ public RawRecordsClient withRawResponse() { /** * Performs multiple record operations in a single transaction. */ - public V1BatchOperationResponse recordServiceBatchOperation(String vaultId) { - return this.rawClient.recordServiceBatchOperation(vaultId).body(); + public BatchOperationResponse batchOperation(String vaultId, BatchOperationRequest request) { + return this.rawClient.batchOperation(vaultId, request).body(); } /** * Performs multiple record operations in a single transaction. */ - public V1BatchOperationResponse recordServiceBatchOperation( - String vaultId, RecordServiceBatchOperationBody request) { - return this.rawClient.recordServiceBatchOperation(vaultId, request).body(); + public BatchOperationResponse batchOperation( + String vaultId, BatchOperationRequest request, RequestOptions requestOptions) { + return this.rawClient.batchOperation(vaultId, request, requestOptions).body(); } /** - * Performs multiple record operations in a single transaction. + * Returns the specified records from a table. */ - public V1BatchOperationResponse recordServiceBatchOperation( - String vaultId, RecordServiceBatchOperationBody request, RequestOptions requestOptions) { - return this.rawClient - .recordServiceBatchOperation(vaultId, request, requestOptions) - .body(); + public BulkGetRecordResponse getRecords(String vaultId, String objectName) { + return this.rawClient.getRecords(vaultId, objectName).body(); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public V1BulkGetRecordResponse recordServiceBulkGetRecord(String vaultId, String objectName) { - return this.rawClient.recordServiceBulkGetRecord(vaultId, objectName).body(); + public BulkGetRecordResponse getRecords(String vaultId, String objectName, RequestOptions requestOptions) { + return this.rawClient.getRecords(vaultId, objectName, requestOptions).body(); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public V1BulkGetRecordResponse recordServiceBulkGetRecord( - String vaultId, String objectName, RecordServiceBulkGetRecordRequest request) { - return this.rawClient - .recordServiceBulkGetRecord(vaultId, objectName, request) - .body(); + public BulkGetRecordResponse getRecords(String vaultId, String objectName, GetRecordsRequest request) { + return this.rawClient.getRecords(vaultId, objectName, request).body(); } /** - * Gets the specified records from a table. + * Returns the specified records from a table. */ - public V1BulkGetRecordResponse recordServiceBulkGetRecord( - String vaultId, - String objectName, - RecordServiceBulkGetRecordRequest request, - RequestOptions requestOptions) { + public BulkGetRecordResponse getRecords( + String vaultId, String objectName, GetRecordsRequest request, RequestOptions requestOptions) { return this.rawClient - .recordServiceBulkGetRecord(vaultId, objectName, request, requestOptions) + .getRecords(vaultId, objectName, request, requestOptions) .body(); } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Inserts a record in the specified table.The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. */ - public V1InsertRecordResponse recordServiceInsertRecord(String vaultId, String objectName) { - return this.rawClient.recordServiceInsertRecord(vaultId, objectName).body(); + public InsertRecordResponse insertRecords(String vaultId, String objectName, InsertRecordRequest request) { + return this.rawClient.insertRecords(vaultId, objectName, request).body(); } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Inserts a record in the specified table.The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. */ - public V1InsertRecordResponse recordServiceInsertRecord( - String vaultId, String objectName, RecordServiceInsertRecordBody request) { + public InsertRecordResponse insertRecords( + String vaultId, String objectName, InsertRecordRequest request, RequestOptions requestOptions) { return this.rawClient - .recordServiceInsertRecord(vaultId, objectName, request) + .insertRecords(vaultId, objectName, request, requestOptions) .body(); } /** - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * Deletes the specified records from a table. */ - public V1InsertRecordResponse recordServiceInsertRecord( - String vaultId, String objectName, RecordServiceInsertRecordBody request, RequestOptions requestOptions) { - return this.rawClient - .recordServiceInsertRecord(vaultId, objectName, request, requestOptions) - .body(); + public BulkDeleteRecordResponse deleteRecords(String vaultId, String objectName) { + return this.rawClient.deleteRecords(vaultId, objectName).body(); } /** * Deletes the specified records from a table. */ - public V1BulkDeleteRecordResponse recordServiceBulkDeleteRecord(String vaultId, String objectName) { - return this.rawClient.recordServiceBulkDeleteRecord(vaultId, objectName).body(); + public BulkDeleteRecordResponse deleteRecords(String vaultId, String objectName, RequestOptions requestOptions) { + return this.rawClient.deleteRecords(vaultId, objectName, requestOptions).body(); } /** * Deletes the specified records from a table. */ - public V1BulkDeleteRecordResponse recordServiceBulkDeleteRecord( - String vaultId, String objectName, RecordServiceBulkDeleteRecordBody request) { - return this.rawClient - .recordServiceBulkDeleteRecord(vaultId, objectName, request) - .body(); + public BulkDeleteRecordResponse deleteRecords(String vaultId, String objectName, BulkDeleteRecordRequest request) { + return this.rawClient.deleteRecords(vaultId, objectName, request).body(); } /** * Deletes the specified records from a table. */ - public V1BulkDeleteRecordResponse recordServiceBulkDeleteRecord( - String vaultId, - String objectName, - RecordServiceBulkDeleteRecordBody request, - RequestOptions requestOptions) { + public BulkDeleteRecordResponse deleteRecords( + String vaultId, String objectName, BulkDeleteRecordRequest request, RequestOptions requestOptions) { return this.rawClient - .recordServiceBulkDeleteRecord(vaultId, objectName, request, requestOptions) + .deleteRecords(vaultId, objectName, request, requestOptions) .body(); } /** * Returns the specified record from a table. */ - public V1FieldRecords recordServiceGetRecord(String vaultId, String objectName, String id) { - return this.rawClient.recordServiceGetRecord(vaultId, objectName, id).body(); + public GetFieldRecords getRecordById(String vaultId, String objectName, String id) { + return this.rawClient.getRecordById(vaultId, objectName, id).body(); } /** * Returns the specified record from a table. */ - public V1FieldRecords recordServiceGetRecord( - String vaultId, String objectName, String id, RecordServiceGetRecordRequest request) { + public GetFieldRecords getRecordById(String vaultId, String objectName, String id, RequestOptions requestOptions) { return this.rawClient - .recordServiceGetRecord(vaultId, objectName, id, request) + .getRecordById(vaultId, objectName, id, requestOptions) .body(); } /** * Returns the specified record from a table. */ - public V1FieldRecords recordServiceGetRecord( - String vaultId, - String objectName, - String id, - RecordServiceGetRecordRequest request, - RequestOptions requestOptions) { - return this.rawClient - .recordServiceGetRecord(vaultId, objectName, id, request, requestOptions) - .body(); - } - - /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. - */ - public V1UpdateRecordResponse recordServiceUpdateRecord(String vaultId, String objectName, String id) { - return this.rawClient.recordServiceUpdateRecord(vaultId, objectName, id).body(); - } - - /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. - */ - public V1UpdateRecordResponse recordServiceUpdateRecord( - String vaultId, String objectName, String id, RecordServiceUpdateRecordBody request) { - return this.rawClient - .recordServiceUpdateRecord(vaultId, objectName, id, request) - .body(); + public GetFieldRecords getRecordById(String vaultId, String objectName, String id, GetRecordByIdRequest request) { + return this.rawClient.getRecordById(vaultId, objectName, id, request).body(); } /** - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * Returns the specified record from a table. */ - public V1UpdateRecordResponse recordServiceUpdateRecord( - String vaultId, - String objectName, - String id, - RecordServiceUpdateRecordBody request, - RequestOptions requestOptions) { + public GetFieldRecords getRecordById( + String vaultId, String objectName, String id, GetRecordByIdRequest request, RequestOptions requestOptions) { return this.rawClient - .recordServiceUpdateRecord(vaultId, objectName, id, request, requestOptions) + .getRecordById(vaultId, objectName, id, request, requestOptions) .body(); } /** - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public V1DeleteRecordResponse recordServiceDeleteRecord(String vaultId, String objectName, String id) { - return this.rawClient.recordServiceDeleteRecord(vaultId, objectName, id).body(); + public UpdateRecordResponse updateRecord(String vaultId, String objectName, String id) { + return this.rawClient.updateRecord(vaultId, objectName, id).body(); } /** - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public V1DeleteRecordResponse recordServiceDeleteRecord( + public UpdateRecordResponse updateRecord( String vaultId, String objectName, String id, RequestOptions requestOptions) { return this.rawClient - .recordServiceDeleteRecord(vaultId, objectName, id, requestOptions) + .updateRecord(vaultId, objectName, id, requestOptions) .body(); } /** - * Uploads a file to the specified record. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public V1UpdateRecordResponse fileServiceUploadFile( - String vaultId, String objectName, String id, Optional file) { - return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, file) - .body(); - } - - /** - * Uploads a file to the specified record. - */ - public V1UpdateRecordResponse fileServiceUploadFile( - String vaultId, String objectName, String id, Optional file, FileServiceUploadFileRequest request) { - return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, file, request) - .body(); + public UpdateRecordResponse updateRecord( + String vaultId, String objectName, String id, UpdateRecordRequest request) { + return this.rawClient.updateRecord(vaultId, objectName, id, request).body(); } /** - * Uploads a file to the specified record. + * Updates the specified record in a table.When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.The time-to-live (TTL) for a transient field resets when the field value is updated. */ - public V1UpdateRecordResponse fileServiceUploadFile( - String vaultId, - String objectName, - String id, - Optional file, - FileServiceUploadFileRequest request, - RequestOptions requestOptions) { + public UpdateRecordResponse updateRecord( + String vaultId, String objectName, String id, UpdateRecordRequest request, RequestOptions requestOptions) { return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, file, request, requestOptions) + .updateRecord(vaultId, objectName, id, request, requestOptions) .body(); } /** - * Deletes a file from the specified record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public V1DeleteFileResponse fileServiceDeleteFile(String vaultId, String tableName, String id, String columnName) { - return this.rawClient - .fileServiceDeleteFile(vaultId, tableName, id, columnName) - .body(); + public DeleteRecordResponse deleteRecord(String vaultId, String objectName, String id) { + return this.rawClient.deleteRecord(vaultId, objectName, id).body(); } /** - * Deletes a file from the specified record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public V1DeleteFileResponse fileServiceDeleteFile( - String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { - return this.rawClient - .fileServiceDeleteFile(vaultId, tableName, id, columnName, requestOptions) - .body(); - } - - /** - * Returns the anti-virus scan status of a file. - */ - public V1GetFileScanStatusResponse fileServiceGetFileScanStatus( - String vaultId, String tableName, String id, String columnName) { - return this.rawClient - .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName) - .body(); - } - - /** - * Returns the anti-virus scan status of a file. - */ - public V1GetFileScanStatusResponse fileServiceGetFileScanStatus( - String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + public DeleteRecordResponse deleteRecord( + String vaultId, String objectName, String id, RequestOptions requestOptions) { return this.rawClient - .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, requestOptions) + .deleteRecord(vaultId, objectName, id, requestOptions) .body(); } /** - * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public UploadFileV2Response uploadFileV2(String vaultId, File file, UploadFileV2Request request) { - return this.rawClient.uploadFileV2(vaultId, file, request).body(); + public DeleteRecordResponse deleteRecord( + String vaultId, String objectName, String id, DeleteRecordRequest request) { + return this.rawClient.deleteRecord(vaultId, objectName, id, request).body(); } /** - * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + * Deletes the specified record from a table.Note: This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. */ - public UploadFileV2Response uploadFileV2( - String vaultId, File file, UploadFileV2Request request, RequestOptions requestOptions) { + public DeleteRecordResponse deleteRecord( + String vaultId, String objectName, String id, DeleteRecordRequest request, RequestOptions requestOptions) { return this.rawClient - .uploadFileV2(vaultId, file, request, requestOptions) + .deleteRecord(vaultId, objectName, id, request, requestOptions) .body(); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/BatchOperationRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/BatchOperationRequest.java new file mode 100644 index 00000000..fb59e148 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/BatchOperationRequest.java @@ -0,0 +1,153 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.BatchRecord; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = BatchOperationRequest.Builder.class) +public final class BatchOperationRequest { + private final List records; + + private final Optional continueOnError; + + private final Map additionalProperties; + + private BatchOperationRequest( + List records, Optional continueOnError, Map additionalProperties) { + this.records = records; + this.continueOnError = continueOnError; + this.additionalProperties = additionalProperties; + } + + /** + * @return Record operations to perform. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + /** + * @return If true, continues processing remaining operations when one operation returns an error. If false, stops processing remaining operations when one operation returns an error. + */ + @JsonProperty("continueOnError") + public Optional getContinueOnError() { + return continueOnError; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof BatchOperationRequest && equalTo((BatchOperationRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(BatchOperationRequest other) { + return records.equals(other.records) && continueOnError.equals(other.continueOnError); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records, this.continueOnError); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List records = new ArrayList<>(); + + private Optional continueOnError = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(BatchOperationRequest other) { + records(other.getRecords()); + continueOnError(other.getContinueOnError()); + return this; + } + + /** + *

                                  Record operations to perform.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(BatchRecord records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + /** + *

                                  If true, continues processing remaining operations when one operation returns an error. If false, stops processing remaining operations when one operation returns an error.

                                  + */ + @JsonSetter(value = "continueOnError", nulls = Nulls.SKIP) + public Builder continueOnError(Optional continueOnError) { + this.continueOnError = continueOnError; + return this; + } + + public Builder continueOnError(Boolean continueOnError) { + this.continueOnError = Optional.ofNullable(continueOnError); + return this; + } + + public BatchOperationRequest build() { + return new BatchOperationRequest(records, continueOnError, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkDeleteRecordBody.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/BulkDeleteRecordRequest.java similarity index 60% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkDeleteRecordBody.java rename to skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/BulkDeleteRecordRequest.java index 4b9dcced..729b0623 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkDeleteRecordBody.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/BulkDeleteRecordRequest.java @@ -3,21 +3,29 @@ */ package com.skyflow.generated.rest.resources.records.requests; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = RecordServiceBulkDeleteRecordBody.Builder.class) -public final class RecordServiceBulkDeleteRecordBody { +@JsonDeserialize(builder = BulkDeleteRecordRequest.Builder.class) +public final class BulkDeleteRecordRequest { private final Optional> skyflowIds; private final Map additionalProperties; - private RecordServiceBulkDeleteRecordBody( - Optional> skyflowIds, Map additionalProperties) { + private BulkDeleteRecordRequest(Optional> skyflowIds, Map additionalProperties) { this.skyflowIds = skyflowIds; this.additionalProperties = additionalProperties; } @@ -30,10 +38,10 @@ public Optional> getSkyflowIds() { return skyflowIds; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof RecordServiceBulkDeleteRecordBody && equalTo((RecordServiceBulkDeleteRecordBody) other); + return other instanceof BulkDeleteRecordRequest && equalTo((BulkDeleteRecordRequest) other); } @JsonAnyGetter @@ -41,16 +49,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(RecordServiceBulkDeleteRecordBody other) { + private boolean equalTo(BulkDeleteRecordRequest other) { return skyflowIds.equals(other.skyflowIds); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.skyflowIds); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -68,7 +76,7 @@ public static final class Builder { private Builder() {} - public Builder from(RecordServiceBulkDeleteRecordBody other) { + public Builder from(BulkDeleteRecordRequest other) { skyflowIds(other.getSkyflowIds()); return this; } @@ -87,8 +95,18 @@ public Builder skyflowIds(List skyflowIds) { return this; } - public RecordServiceBulkDeleteRecordBody build() { - return new RecordServiceBulkDeleteRecordBody(skyflowIds, additionalProperties); + public BulkDeleteRecordRequest build() { + return new BulkDeleteRecordRequest(skyflowIds, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/DeleteRecordRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/DeleteRecordRequest.java new file mode 100644 index 00000000..eedbaef7 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/DeleteRecordRequest.java @@ -0,0 +1,69 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeleteRecordRequest.Builder.class) +public final class DeleteRecordRequest { + private final Map additionalProperties; + + private DeleteRecordRequest(Map additionalProperties) { + this.additionalProperties = additionalProperties; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeleteRecordRequest; + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DeleteRecordRequest other) { + return this; + } + + public DeleteRecordRequest build() { + return new DeleteRecordRequest(additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/DeleteRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/DeleteRequest.java new file mode 100644 index 00000000..3a620b09 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/DeleteRequest.java @@ -0,0 +1,263 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.UniqueValue; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeleteRequest.Builder.class) +public final class DeleteRequest { + private final String vaultId; + + private final Optional tableName; + + private final Optional> skyflowIDs; + + private final Optional> uniqueValues; + + private final Map additionalProperties; + + private DeleteRequest( + String vaultId, + Optional tableName, + Optional> skyflowIDs, + Optional> uniqueValues, + Map additionalProperties) { + this.vaultId = vaultId; + this.tableName = tableName; + this.skyflowIDs = skyflowIDs; + this.uniqueValues = uniqueValues; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Name of the table. + */ + @JsonProperty("tableName") + public Optional getTableName() { + return tableName; + } + + /** + * @return Skyflow IDs of the records to delete. + */ + @JsonProperty("skyflowIDs") + public Optional> getSkyflowIDs() { + return skyflowIDs; + } + + /** + * @return List of unique constraint values to query records by data. + */ + @JsonProperty("uniqueValues") + public Optional> getUniqueValues() { + return uniqueValues; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeleteRequest && equalTo((DeleteRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeleteRequest other) { + return vaultId.equals(other.vaultId) + && tableName.equals(other.tableName) + && skyflowIDs.equals(other.skyflowIDs) + && uniqueValues.equals(other.uniqueValues); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.tableName, this.skyflowIDs, this.uniqueValues); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault.

                                  + */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(DeleteRequest other); + } + + public interface _FinalStage { + DeleteRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Name of the table.

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

                                  Skyflow IDs of the records to delete.

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

                                  List of unique constraint values to query records by data.

                                  + */ + _FinalStage uniqueValues(Optional> uniqueValues); + + _FinalStage uniqueValues(List uniqueValues); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private Optional> uniqueValues = Optional.empty(); + + private Optional> skyflowIDs = Optional.empty(); + + private Optional tableName = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeleteRequest other) { + vaultId(other.getVaultId()); + tableName(other.getTableName()); + skyflowIDs(other.getSkyflowIDs()); + uniqueValues(other.getUniqueValues()); + return this; + } + + /** + *

                                  ID of the vault.

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

                                  List of unique constraint values to query records by data.

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

                                  List of unique constraint values to query records by data.

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

                                  Skyflow IDs of the records to delete.

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

                                  Skyflow IDs of the records to delete.

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

                                  Name of the table.

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

                                  Name of the table.

                                  + */ + @java.lang.Override + @JsonSetter(value = "tableName", nulls = Nulls.SKIP) + public _FinalStage tableName(Optional tableName) { + this.tableName = tableName; + return this; + } + + @java.lang.Override + public DeleteRequest build() { + return new DeleteRequest(vaultId, tableName, skyflowIDs, uniqueValues, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java deleted file mode 100644 index 3efb0a98..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.records.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = FileServiceUploadFileRequest.Builder.class) -public final class FileServiceUploadFileRequest { - private final Optional columnName; - - private final Map additionalProperties; - - private FileServiceUploadFileRequest(Optional columnName, Map additionalProperties) { - this.columnName = columnName; - this.additionalProperties = additionalProperties; - } - - /** - * @return Name of the column to store the file in. The column must have a file data type. - */ - @JsonProperty("columnName") - public Optional getColumnName() { - return columnName; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof FileServiceUploadFileRequest && equalTo((FileServiceUploadFileRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(FileServiceUploadFileRequest other) { - return columnName.equals(other.columnName); - } - - @Override - public int hashCode() { - return Objects.hash(this.columnName); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional columnName = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(FileServiceUploadFileRequest other) { - columnName(other.getColumnName()); - return this; - } - - /** - *

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

                                  - */ - @JsonSetter(value = "columnName", nulls = Nulls.SKIP) - public Builder columnName(Optional columnName) { - this.columnName = columnName; - return this; - } - - public Builder columnName(String columnName) { - this.columnName = Optional.ofNullable(columnName); - return this; - } - - public FileServiceUploadFileRequest build() { - return new FileServiceUploadFileRequest(columnName, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceGetRecordRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRecordByIdRequest.java similarity index 57% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceGetRecordRequest.java rename to skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRecordByIdRequest.java index 91317d02..db5cd9aa 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceGetRecordRequest.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRecordByIdRequest.java @@ -3,75 +3,82 @@ */ package com.skyflow.generated.rest.resources.records.requests; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.records.types.RecordServiceGetRecordRequestRedaction; - -import java.util.*; +import com.skyflow.generated.rest.resources.records.types.GetRecordByIdRequestRedaction; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = RecordServiceGetRecordRequest.Builder.class) -public final class RecordServiceGetRecordRequest { +@JsonDeserialize(builder = GetRecordByIdRequest.Builder.class) +public final class GetRecordByIdRequest { private final Optional> fields; - private final Optional redaction; + private final Optional redaction; private final Optional tokenization; private final Optional downloadUrl; + private final Optional returnFileMetadata; + private final Map additionalProperties; - private RecordServiceGetRecordRequest( + private GetRecordByIdRequest( Optional> fields, - Optional redaction, + Optional redaction, Optional tokenization, Optional downloadUrl, + Optional returnFileMetadata, Map additionalProperties) { this.fields = fields; this.redaction = redaction; this.tokenization = tokenization; this.downloadUrl = downloadUrl; + this.returnFileMetadata = returnFileMetadata; this.additionalProperties = additionalProperties; } - /** - * @return Fields to return for the record, with one value per fields URL parameter. For example, ?fields=abc&fields=123.<br /><br />If not specified, returns all fields. - */ @JsonProperty("fields") public Optional> getFields() { return fields; } - /** - * @return Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. - */ @JsonProperty("redaction") - public Optional getRedaction() { + public Optional getRedaction() { return redaction; } - /** - * @return If true, this operation returns tokens for fields with tokenization enabled. Only applicable if skyflow_id values are specified. - */ @JsonProperty("tokenization") public Optional getTokenization() { return tokenization; } - /** - * @return If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - */ @JsonProperty("downloadURL") public Optional getDownloadUrl() { return downloadUrl; } - @Override + @JsonProperty("returnFileMetadata") + public Optional getReturnFileMetadata() { + return returnFileMetadata; + } + + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof RecordServiceGetRecordRequest && equalTo((RecordServiceGetRecordRequest) other); + return other instanceof GetRecordByIdRequest && equalTo((GetRecordByIdRequest) other); } @JsonAnyGetter @@ -79,19 +86,20 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(RecordServiceGetRecordRequest other) { + private boolean equalTo(GetRecordByIdRequest other) { return fields.equals(other.fields) && redaction.equals(other.redaction) && tokenization.equals(other.tokenization) - && downloadUrl.equals(other.downloadUrl); + && downloadUrl.equals(other.downloadUrl) + && returnFileMetadata.equals(other.returnFileMetadata); } - @Override + @java.lang.Override public int hashCode() { - return Objects.hash(this.fields, this.redaction, this.tokenization, this.downloadUrl); + return Objects.hash(this.fields, this.redaction, this.tokenization, this.downloadUrl, this.returnFileMetadata); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -104,28 +112,28 @@ public static Builder builder() { public static final class Builder { private Optional> fields = Optional.empty(); - private Optional redaction = Optional.empty(); + private Optional redaction = Optional.empty(); private Optional tokenization = Optional.empty(); private Optional downloadUrl = Optional.empty(); + private Optional returnFileMetadata = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} - public Builder from(RecordServiceGetRecordRequest other) { + public Builder from(GetRecordByIdRequest other) { fields(other.getFields()); redaction(other.getRedaction()); tokenization(other.getTokenization()); downloadUrl(other.getDownloadUrl()); + returnFileMetadata(other.getReturnFileMetadata()); return this; } - /** - *

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

                                  - */ @JsonSetter(value = "fields", nulls = Nulls.SKIP) public Builder fields(Optional> fields) { this.fields = fields; @@ -142,23 +150,17 @@ public Builder fields(String fields) { return this; } - /** - *

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

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

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

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

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

                                  - */ @JsonSetter(value = "downloadURL", nulls = Nulls.SKIP) public Builder downloadUrl(Optional downloadUrl) { this.downloadUrl = downloadUrl; @@ -184,9 +183,30 @@ public Builder downloadUrl(Boolean downloadUrl) { return this; } - public RecordServiceGetRecordRequest build() { - return new RecordServiceGetRecordRequest( - fields, redaction, tokenization, downloadUrl, additionalProperties); + @JsonSetter(value = "returnFileMetadata", nulls = Nulls.SKIP) + public Builder returnFileMetadata(Optional returnFileMetadata) { + this.returnFileMetadata = returnFileMetadata; + return this; + } + + public Builder returnFileMetadata(Boolean returnFileMetadata) { + this.returnFileMetadata = Optional.ofNullable(returnFileMetadata); + return this; + } + + public GetRecordByIdRequest build() { + return new GetRecordByIdRequest( + fields, redaction, tokenization, downloadUrl, returnFileMetadata, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkGetRecordRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRecordsRequest.java similarity index 59% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkGetRecordRequest.java rename to skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRecordsRequest.java index 9b59168a..f6e9263a 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkGetRecordRequest.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRecordsRequest.java @@ -3,24 +3,34 @@ */ package com.skyflow.generated.rest.resources.records.requests; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestOrderBy; -import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestRedaction; - -import java.util.*; +import com.skyflow.generated.rest.resources.records.types.GetRecordsRequestOrderBy; +import com.skyflow.generated.rest.resources.records.types.GetRecordsRequestRedaction; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = RecordServiceBulkGetRecordRequest.Builder.class) -public final class RecordServiceBulkGetRecordRequest { +@JsonDeserialize(builder = GetRecordsRequest.Builder.class) +public final class GetRecordsRequest { private final Optional> skyflowIds; private final Optional> fields; private final Optional> columnValues; - private final Optional redaction; + private final Optional redaction; private final Optional tokenization; @@ -32,21 +42,24 @@ public final class RecordServiceBulkGetRecordRequest { private final Optional columnName; - private final Optional orderBy; + private final Optional orderBy; + + private final Optional returnFileMetadata; private final Map additionalProperties; - private RecordServiceBulkGetRecordRequest( + private GetRecordsRequest( Optional> skyflowIds, Optional> fields, Optional> columnValues, - Optional redaction, + Optional redaction, Optional tokenization, Optional offset, Optional limit, Optional downloadUrl, Optional columnName, - Optional orderBy, + Optional orderBy, + Optional returnFileMetadata, Map additionalProperties) { this.skyflowIds = skyflowIds; this.fields = fields; @@ -58,93 +71,69 @@ private RecordServiceBulkGetRecordRequest( this.downloadUrl = downloadUrl; this.columnName = columnName; this.orderBy = orderBy; + this.returnFileMetadata = returnFileMetadata; this.additionalProperties = additionalProperties; } - /** - * @return skyflow_id values of the records to return, with one value per skyflow_ids URL parameter. For example, ?skyflow_ids=abc&skyflow_ids=123.<br /><br />If not specified, returns the first 25 records in the table. - */ @JsonProperty("skyflow_ids") public Optional> getSkyflowIds() { return skyflowIds; } - /** - * @return Fields to return for the record, with one value per fields URL parameter. For example, ?fields=abc&fields=123.<br /><br />If not specified, returns all fields. - */ @JsonProperty("fields") public Optional> getFields() { return fields; } - /** - * @return Column values of the records to return, with one value per column_values URL parameter. For example, ?column_values=abc&column_values=123.<br /><br />column_name is mandatory when providing column_values. If you use column name or column value, you cannot use skyflow_ids. Passing either of these parameters with skyflow_ids returns an error. - */ @JsonProperty("column_values") public Optional> getColumnValues() { return columnValues; } - /** - * @return Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. - */ @JsonProperty("redaction") - public Optional getRedaction() { + public Optional getRedaction() { return redaction; } - /** - * @return If true, this operation returns tokens for fields with tokenization enabled. Only applicable if skyflow_id values are specified. - */ @JsonProperty("tokenization") public Optional getTokenization() { return tokenization; } - /** - * @return Record position at which to start receiving data. - */ @JsonProperty("offset") public Optional getOffset() { return offset; } - /** - * @return Number of record to return. Maximum 25. - */ @JsonProperty("limit") public Optional getLimit() { return limit; } - /** - * @return If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - */ @JsonProperty("downloadURL") public Optional getDownloadUrl() { return downloadUrl; } - /** - * @return Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use skyflow_ids. Passing either of these parameters with skyflow_ids returns an error. - */ @JsonProperty("column_name") public Optional getColumnName() { return columnName; } - /** - * @return Order to return records, based on skyflow_id values. To disable, set to NONE. - */ @JsonProperty("order_by") - public Optional getOrderBy() { + public Optional getOrderBy() { return orderBy; } - @Override + @JsonProperty("returnFileMetadata") + public Optional getReturnFileMetadata() { + return returnFileMetadata; + } + + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof RecordServiceBulkGetRecordRequest && equalTo((RecordServiceBulkGetRecordRequest) other); + return other instanceof GetRecordsRequest && equalTo((GetRecordsRequest) other); } @JsonAnyGetter @@ -152,7 +141,7 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(RecordServiceBulkGetRecordRequest other) { + private boolean equalTo(GetRecordsRequest other) { return skyflowIds.equals(other.skyflowIds) && fields.equals(other.fields) && columnValues.equals(other.columnValues) @@ -162,10 +151,11 @@ private boolean equalTo(RecordServiceBulkGetRecordRequest other) { && limit.equals(other.limit) && downloadUrl.equals(other.downloadUrl) && columnName.equals(other.columnName) - && orderBy.equals(other.orderBy); + && orderBy.equals(other.orderBy) + && returnFileMetadata.equals(other.returnFileMetadata); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash( this.skyflowIds, @@ -177,10 +167,11 @@ public int hashCode() { this.limit, this.downloadUrl, this.columnName, - this.orderBy); + this.orderBy, + this.returnFileMetadata); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -197,7 +188,7 @@ public static final class Builder { private Optional> columnValues = Optional.empty(); - private Optional redaction = Optional.empty(); + private Optional redaction = Optional.empty(); private Optional tokenization = Optional.empty(); @@ -209,14 +200,16 @@ public static final class Builder { private Optional columnName = Optional.empty(); - private Optional orderBy = Optional.empty(); + private Optional orderBy = Optional.empty(); + + private Optional returnFileMetadata = Optional.empty(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} - public Builder from(RecordServiceBulkGetRecordRequest other) { + public Builder from(GetRecordsRequest other) { skyflowIds(other.getSkyflowIds()); fields(other.getFields()); columnValues(other.getColumnValues()); @@ -227,12 +220,10 @@ public Builder from(RecordServiceBulkGetRecordRequest other) { downloadUrl(other.getDownloadUrl()); columnName(other.getColumnName()); orderBy(other.getOrderBy()); + returnFileMetadata(other.getReturnFileMetadata()); return this; } - /** - *

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

                                  - */ @JsonSetter(value = "skyflow_ids", nulls = Nulls.SKIP) public Builder skyflowIds(Optional> skyflowIds) { this.skyflowIds = skyflowIds; @@ -249,9 +240,6 @@ public Builder skyflowIds(String skyflowIds) { return this; } - /** - *

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

                                  - */ @JsonSetter(value = "fields", nulls = Nulls.SKIP) public Builder fields(Optional> fields) { this.fields = fields; @@ -268,9 +256,6 @@ public Builder fields(String fields) { return this; } - /** - *

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

                                  - */ @JsonSetter(value = "column_values", nulls = Nulls.SKIP) public Builder columnValues(Optional> columnValues) { this.columnValues = columnValues; @@ -287,23 +272,17 @@ public Builder columnValues(String columnValues) { return this; } - /** - *

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

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

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

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

                                  Record position at which to start receiving data.

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

                                  Number of record to return. Maximum 25.

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

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

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

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

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

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

                                  - */ @JsonSetter(value = "order_by", nulls = Nulls.SKIP) - public Builder orderBy(Optional orderBy) { + public Builder orderBy(Optional orderBy) { this.orderBy = orderBy; return this; } - public Builder orderBy(RecordServiceBulkGetRecordRequestOrderBy orderBy) { + public Builder orderBy(GetRecordsRequestOrderBy orderBy) { this.orderBy = Optional.ofNullable(orderBy); return this; } - public RecordServiceBulkGetRecordRequest build() { - return new RecordServiceBulkGetRecordRequest( + @JsonSetter(value = "returnFileMetadata", nulls = Nulls.SKIP) + public Builder returnFileMetadata(Optional returnFileMetadata) { + this.returnFileMetadata = returnFileMetadata; + return this; + } + + public Builder returnFileMetadata(Boolean returnFileMetadata) { + this.returnFileMetadata = Optional.ofNullable(returnFileMetadata); + return this; + } + + public GetRecordsRequest build() { + return new GetRecordsRequest( skyflowIds, fields, columnValues, @@ -397,7 +372,18 @@ public RecordServiceBulkGetRecordRequest build() { downloadUrl, columnName, orderBy, + returnFileMetadata, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRequest.java new file mode 100644 index 00000000..e6290a9d --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/GetRequest.java @@ -0,0 +1,499 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.ColumnRedactions; +import com.skyflow.generated.rest.types.GetRequestData; +import com.skyflow.generated.rest.types.UniqueValue; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetRequest.Builder.class) +public final class GetRequest { + private final String vaultId; + + private final Optional tableName; + + private final Optional> skyflowIDs; + + private final Optional> columnRedactions; + + private final Optional> columns; + + private final Optional limit; + + private final Optional offset; + + private final Optional> uniqueValues; + + private final Optional> records; + + private final Map additionalProperties; + + private GetRequest( + String vaultId, + Optional tableName, + Optional> skyflowIDs, + Optional> columnRedactions, + Optional> columns, + Optional limit, + Optional offset, + Optional> uniqueValues, + Optional> records, + Map additionalProperties) { + this.vaultId = vaultId; + this.tableName = tableName; + this.skyflowIDs = skyflowIDs; + this.columnRedactions = columnRedactions; + this.columns = columns; + this.limit = limit; + this.offset = offset; + this.uniqueValues = uniqueValues; + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Name of the table to perform the operation on. + */ + @JsonProperty("tableName") + public Optional getTableName() { + return tableName; + } + + /** + * @return Skyflow IDs of the records to return. Either skyflowIDs or uniqueValues are required. If both are provided, the request fails. + */ + @JsonProperty("skyflowIDs") + public Optional> getSkyflowIDs() { + return skyflowIDs; + } + + /** + * @return List of columns to redact. + */ + @JsonProperty("columnRedactions") + public Optional> getColumnRedactions() { + return columnRedactions; + } + + /** + * @return List of columns to return. + */ + @JsonProperty("columns") + public Optional> getColumns() { + return columns; + } + + /** + * @return Limit for the number of records to be fetched. + */ + @JsonProperty("limit") + public Optional getLimit() { + return limit; + } + + /** + * @return Offset for the number of records to be fetched. + */ + @JsonProperty("offset") + public Optional getOffset() { + return offset; + } + + /** + * @return List of unique constraint values to query records by data. + */ + @JsonProperty("uniqueValues") + public Optional> getUniqueValues() { + return uniqueValues; + } + + /** + * @return List of records to be fetched. This field contains tableName and skyflowIDs belonging to the table. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetRequest && equalTo((GetRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetRequest other) { + return vaultId.equals(other.vaultId) + && tableName.equals(other.tableName) + && skyflowIDs.equals(other.skyflowIDs) + && columnRedactions.equals(other.columnRedactions) + && columns.equals(other.columns) + && limit.equals(other.limit) + && offset.equals(other.offset) + && uniqueValues.equals(other.uniqueValues) + && records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.tableName, + this.skyflowIDs, + this.columnRedactions, + this.columns, + this.limit, + this.offset, + this.uniqueValues, + this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault.

                                  + */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(GetRequest other); + } + + public interface _FinalStage { + GetRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Name of the table to perform the operation on.

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

                                  Skyflow IDs of the records to return. Either skyflowIDs or uniqueValues are required. If both are provided, the request fails.

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

                                  List of columns to redact.

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

                                  List of columns to return.

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

                                  Limit for the number of records to be fetched.

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

                                  Offset for the number of records to be fetched.

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

                                  List of unique constraint values to query records by data.

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

                                  List of records to be fetched. This field contains tableName and skyflowIDs belonging to the table.

                                  + */ + _FinalStage records(Optional> records); + + _FinalStage records(List records); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private Optional> records = Optional.empty(); + + private Optional> uniqueValues = Optional.empty(); + + private Optional offset = Optional.empty(); + + private Optional limit = Optional.empty(); + + private Optional> columns = Optional.empty(); + + private Optional> columnRedactions = Optional.empty(); + + private Optional> skyflowIDs = Optional.empty(); + + private Optional tableName = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(GetRequest other) { + vaultId(other.getVaultId()); + tableName(other.getTableName()); + skyflowIDs(other.getSkyflowIDs()); + columnRedactions(other.getColumnRedactions()); + columns(other.getColumns()); + limit(other.getLimit()); + offset(other.getOffset()); + uniqueValues(other.getUniqueValues()); + records(other.getRecords()); + return this; + } + + /** + *

                                  ID of the vault.

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

                                  List of records to be fetched. This field contains tableName and skyflowIDs belonging to the table.

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

                                  List of records to be fetched. This field contains tableName and skyflowIDs belonging to the table.

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

                                  List of unique constraint values to query records by data.

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

                                  List of unique constraint values to query records by data.

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

                                  Offset for the number of records to be fetched.

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

                                  Offset for the number of records to be fetched.

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

                                  Limit for the number of records to be fetched.

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

                                  Limit for the number of records to be fetched.

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

                                  List of columns to return.

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

                                  List of columns to return.

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

                                  List of columns to redact.

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

                                  List of columns to redact.

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

                                  Skyflow IDs of the records to return. Either skyflowIDs or uniqueValues are required. If both are provided, the request fails.

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

                                  Skyflow IDs of the records to return. Either skyflowIDs or uniqueValues are required. If both are provided, the request fails.

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

                                  Name of the table to perform the operation on.

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

                                  Name of the table to perform the operation on.

                                  + */ + @java.lang.Override + @JsonSetter(value = "tableName", nulls = Nulls.SKIP) + public _FinalStage tableName(Optional tableName) { + this.tableName = tableName; + return this; + } + + @java.lang.Override + public GetRequest build() { + return new GetRequest( + vaultId, + tableName, + skyflowIDs, + columnRedactions, + columns, + limit, + offset, + uniqueValues, + records, + additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceInsertRecordBody.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/InsertRecordRequest.java similarity index 63% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceInsertRecordBody.java rename to skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/InsertRecordRequest.java index e832e396..a842c058 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceInsertRecordBody.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/InsertRecordRequest.java @@ -3,18 +3,28 @@ */ package com.skyflow.generated.rest.resources.records.requests; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.types.V1Byot; -import com.skyflow.generated.rest.types.V1FieldRecords; - -import java.util.*; +import com.skyflow.generated.rest.resources.records.types.InsertRecordRequestByot; +import com.skyflow.generated.rest.types.FieldRecords; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = RecordServiceInsertRecordBody.Builder.class) -public final class RecordServiceInsertRecordBody { - private final Optional> records; +@JsonDeserialize(builder = InsertRecordRequest.Builder.class) +public final class InsertRecordRequest { + private final List records; private final Optional tokenization; @@ -22,16 +32,16 @@ public final class RecordServiceInsertRecordBody { private final Optional homogeneous; - private final Optional byot; + private final Optional byot; private final Map additionalProperties; - private RecordServiceInsertRecordBody( - Optional> records, + private InsertRecordRequest( + List records, Optional tokenization, Optional upsert, Optional homogeneous, - Optional byot, + Optional byot, Map additionalProperties) { this.records = records; this.tokenization = tokenization; @@ -45,7 +55,7 @@ private RecordServiceInsertRecordBody( * @return Record values and tokens. */ @JsonProperty("records") - public Optional> getRecords() { + public List getRecords() { return records; } @@ -58,7 +68,7 @@ public Optional getTokenization() { } /** - * @return Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.<br /><br />When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. + * @return Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. */ @JsonProperty("upsert") public Optional getUpsert() { @@ -73,15 +83,18 @@ public Optional getHomogeneous() { return homogeneous; } + /** + * @return Token insertion behavior. + */ @JsonProperty("byot") - public Optional getByot() { + public Optional getByot() { return byot; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof RecordServiceInsertRecordBody && equalTo((RecordServiceInsertRecordBody) other); + return other instanceof InsertRecordRequest && equalTo((InsertRecordRequest) other); } @JsonAnyGetter @@ -89,7 +102,7 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(RecordServiceInsertRecordBody other) { + private boolean equalTo(InsertRecordRequest other) { return records.equals(other.records) && tokenization.equals(other.tokenization) && upsert.equals(other.upsert) @@ -97,12 +110,12 @@ private boolean equalTo(RecordServiceInsertRecordBody other) { && byot.equals(other.byot); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.records, this.tokenization, this.upsert, this.homogeneous, this.byot); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -113,7 +126,7 @@ public static Builder builder() { @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder { - private Optional> records = Optional.empty(); + private List records = new ArrayList<>(); private Optional tokenization = Optional.empty(); @@ -121,14 +134,14 @@ public static final class Builder { private Optional homogeneous = Optional.empty(); - private Optional byot = Optional.empty(); + private Optional byot = Optional.empty(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} - public Builder from(RecordServiceInsertRecordBody other) { + public Builder from(InsertRecordRequest other) { records(other.getRecords()); tokenization(other.getTokenization()); upsert(other.getUpsert()); @@ -141,13 +154,23 @@ public Builder from(RecordServiceInsertRecordBody other) { *

                                  Record values and tokens.

                                  */ @JsonSetter(value = "records", nulls = Nulls.SKIP) - public Builder records(Optional> records) { - this.records = records; + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } return this; } - public Builder records(List records) { - this.records = Optional.ofNullable(records); + public Builder addRecords(FieldRecords records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } return this; } @@ -166,7 +189,7 @@ public Builder tokenization(Boolean tokenization) { } /** - *

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

                                  + *

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

                                  */ @JsonSetter(value = "upsert", nulls = Nulls.SKIP) public Builder upsert(Optional upsert) { @@ -193,20 +216,32 @@ public Builder homogeneous(Boolean homogeneous) { return this; } + /** + *

                                  Token insertion behavior.

                                  + */ @JsonSetter(value = "byot", nulls = Nulls.SKIP) - public Builder byot(Optional byot) { + public Builder byot(Optional byot) { this.byot = byot; return this; } - public Builder byot(V1Byot byot) { + public Builder byot(InsertRecordRequestByot byot) { this.byot = Optional.ofNullable(byot); return this; } - public RecordServiceInsertRecordBody build() { - return new RecordServiceInsertRecordBody( - records, tokenization, upsert, homogeneous, byot, additionalProperties); + public InsertRecordRequest build() { + return new InsertRecordRequest(records, tokenization, upsert, homogeneous, byot, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/InsertRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/InsertRequest.java new file mode 100644 index 00000000..c4db785e --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/InsertRequest.java @@ -0,0 +1,260 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.InsertRecordData; +import com.skyflow.generated.rest.types.Upsert; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = InsertRequest.Builder.class) +public final class InsertRequest { + private final String vaultId; + + private final String tableName; + + private final List records; + + private final Optional upsert; + + private final Map additionalProperties; + + private InsertRequest( + String vaultId, + String tableName, + List records, + Optional upsert, + Map additionalProperties) { + this.vaultId = vaultId; + this.tableName = tableName; + this.records = records; + this.upsert = upsert; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Name of the table to perform the operation on. Can be defined at both the request body level and individual record level. If provided at both levels, the record-level tableName takes precedence. + */ + @JsonProperty("tableName") + public String getTableName() { + return tableName; + } + + /** + * @return Data to insert as a list of records. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @JsonProperty("upsert") + public Optional getUpsert() { + return upsert; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof InsertRequest && equalTo((InsertRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(InsertRequest other) { + return vaultId.equals(other.vaultId) + && tableName.equals(other.tableName) + && records.equals(other.records) + && upsert.equals(other.upsert); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.tableName, this.records, this.upsert); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault.

                                  + */ + TableNameStage vaultId(@NotNull String vaultId); + + Builder from(InsertRequest other); + } + + public interface TableNameStage { + /** + *

                                  Name of the table to perform the operation on. Can be defined at both the request body level and individual record level. If provided at both levels, the record-level tableName takes precedence.

                                  + */ + _FinalStage tableName(@NotNull String tableName); + } + + public interface _FinalStage { + InsertRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Data to insert as a list of records.

                                  + */ + _FinalStage records(List records); + + _FinalStage addRecords(InsertRecordData records); + + _FinalStage addAllRecords(List records); + + _FinalStage upsert(Optional upsert); + + _FinalStage upsert(Upsert upsert); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, TableNameStage, _FinalStage { + private String vaultId; + + private String tableName; + + private Optional upsert = Optional.empty(); + + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(InsertRequest other) { + vaultId(other.getVaultId()); + tableName(other.getTableName()); + records(other.getRecords()); + upsert(other.getUpsert()); + return this; + } + + /** + *

                                  ID of the vault.

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

                                  Name of the table to perform the operation on. Can be defined at both the request body level and individual record level. If provided at both levels, the record-level tableName takes precedence.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("tableName") + public _FinalStage tableName(@NotNull String tableName) { + this.tableName = Objects.requireNonNull(tableName, "tableName must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage upsert(Upsert upsert) { + this.upsert = Optional.ofNullable(upsert); + return this; + } + + @java.lang.Override + @JsonSetter(value = "upsert", nulls = Nulls.SKIP) + public _FinalStage upsert(Optional upsert) { + this.upsert = upsert; + return this; + } + + /** + *

                                  Data to insert as a list of records.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + /** + *

                                  Data to insert as a list of records.

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

                                  Data to insert as a list of records.

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

                                  Record operations to perform.

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

                                  Continue performing operations on partial errors.

                                  - */ - @JsonSetter(value = "continueOnError", nulls = Nulls.SKIP) - public Builder continueOnError(Optional continueOnError) { - this.continueOnError = continueOnError; - return this; - } - - public Builder continueOnError(Boolean continueOnError) { - this.continueOnError = Optional.ofNullable(continueOnError); - return this; - } - - @JsonSetter(value = "byot", nulls = Nulls.SKIP) - public Builder byot(Optional byot) { - this.byot = byot; - return this; - } - - public Builder byot(V1Byot byot) { - this.byot = Optional.ofNullable(byot); - return this; - } - - public RecordServiceBatchOperationBody build() { - return new RecordServiceBatchOperationBody(records, continueOnError, byot, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceUpdateRecordBody.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UpdateRecordRequest.java similarity index 58% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceUpdateRecordBody.java rename to skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UpdateRecordRequest.java index f5c7a229..2e22ed53 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceUpdateRecordBody.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UpdateRecordRequest.java @@ -3,32 +3,37 @@ */ package com.skyflow.generated.rest.resources.records.requests; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.types.V1Byot; -import com.skyflow.generated.rest.types.V1FieldRecords; - +import com.skyflow.generated.rest.resources.records.types.UpdateRecordRequestByot; +import com.skyflow.generated.rest.types.FieldRecords; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = RecordServiceUpdateRecordBody.Builder.class) -public final class RecordServiceUpdateRecordBody { - private final Optional record; +@JsonDeserialize(builder = UpdateRecordRequest.Builder.class) +public final class UpdateRecordRequest { + private final Optional record; private final Optional tokenization; - private final Optional byot; + private final Optional byot; private final Map additionalProperties; - private RecordServiceUpdateRecordBody( - Optional record, + private UpdateRecordRequest( + Optional record, Optional tokenization, - Optional byot, + Optional byot, Map additionalProperties) { this.record = record; this.tokenization = tokenization; @@ -37,7 +42,7 @@ private RecordServiceUpdateRecordBody( } @JsonProperty("record") - public Optional getRecord() { + public Optional getRecord() { return record; } @@ -49,15 +54,18 @@ public Optional getTokenization() { return tokenization; } + /** + * @return Token insertion behavior. + */ @JsonProperty("byot") - public Optional getByot() { + public Optional getByot() { return byot; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof RecordServiceUpdateRecordBody && equalTo((RecordServiceUpdateRecordBody) other); + return other instanceof UpdateRecordRequest && equalTo((UpdateRecordRequest) other); } @JsonAnyGetter @@ -65,16 +73,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(RecordServiceUpdateRecordBody other) { + private boolean equalTo(UpdateRecordRequest other) { return record.equals(other.record) && tokenization.equals(other.tokenization) && byot.equals(other.byot); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.record, this.tokenization, this.byot); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -85,18 +93,18 @@ public static Builder builder() { @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder { - private Optional record = Optional.empty(); + private Optional record = Optional.empty(); private Optional tokenization = Optional.empty(); - private Optional byot = Optional.empty(); + private Optional byot = Optional.empty(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} - public Builder from(RecordServiceUpdateRecordBody other) { + public Builder from(UpdateRecordRequest other) { record(other.getRecord()); tokenization(other.getTokenization()); byot(other.getByot()); @@ -104,12 +112,12 @@ public Builder from(RecordServiceUpdateRecordBody other) { } @JsonSetter(value = "record", nulls = Nulls.SKIP) - public Builder record(Optional record) { + public Builder record(Optional record) { this.record = record; return this; } - public Builder record(V1FieldRecords record) { + public Builder record(FieldRecords record) { this.record = Optional.ofNullable(record); return this; } @@ -128,19 +136,32 @@ public Builder tokenization(Boolean tokenization) { return this; } + /** + *

                                  Token insertion behavior.

                                  + */ @JsonSetter(value = "byot", nulls = Nulls.SKIP) - public Builder byot(Optional byot) { + public Builder byot(Optional byot) { this.byot = byot; return this; } - public Builder byot(V1Byot byot) { + public Builder byot(UpdateRecordRequestByot byot) { this.byot = Optional.ofNullable(byot); return this; } - public RecordServiceUpdateRecordBody build() { - return new RecordServiceUpdateRecordBody(record, tokenization, byot, additionalProperties); + public UpdateRecordRequest build() { + return new UpdateRecordRequest(record, tokenization, byot, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UpdateRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UpdateRequest.java new file mode 100644 index 00000000..6b7f32c7 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/requests/UpdateRequest.java @@ -0,0 +1,273 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.records.types.UpdateRequestUpdateType; +import com.skyflow.generated.rest.types.UpdateRecordData; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = UpdateRequest.Builder.class) +public final class UpdateRequest { + private final String vaultId; + + private final String tableName; + + private final List records; + + private final Optional updateType; + + private final Map additionalProperties; + + private UpdateRequest( + String vaultId, + String tableName, + List records, + Optional updateType, + Map additionalProperties) { + this.vaultId = vaultId; + this.tableName = tableName; + this.records = records; + this.updateType = updateType; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Name of the table. + */ + @JsonProperty("tableName") + public String getTableName() { + return tableName; + } + + /** + * @return Data to update as a list of records. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + /** + * @return Type of update operation to perform. + */ + @JsonProperty("updateType") + public Optional getUpdateType() { + return updateType; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof UpdateRequest && equalTo((UpdateRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(UpdateRequest other) { + return vaultId.equals(other.vaultId) + && tableName.equals(other.tableName) + && records.equals(other.records) + && updateType.equals(other.updateType); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.tableName, this.records, this.updateType); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault.

                                  + */ + TableNameStage vaultId(@NotNull String vaultId); + + Builder from(UpdateRequest other); + } + + public interface TableNameStage { + /** + *

                                  Name of the table.

                                  + */ + _FinalStage tableName(@NotNull String tableName); + } + + public interface _FinalStage { + UpdateRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Data to update as a list of records.

                                  + */ + _FinalStage records(List records); + + _FinalStage addRecords(UpdateRecordData records); + + _FinalStage addAllRecords(List records); + + /** + *

                                  Type of update operation to perform.

                                  + */ + _FinalStage updateType(Optional updateType); + + _FinalStage updateType(UpdateRequestUpdateType updateType); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, TableNameStage, _FinalStage { + private String vaultId; + + private String tableName; + + private Optional updateType = Optional.empty(); + + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(UpdateRequest other) { + vaultId(other.getVaultId()); + tableName(other.getTableName()); + records(other.getRecords()); + updateType(other.getUpdateType()); + return this; + } + + /** + *

                                  ID of the vault.

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

                                  Name of the table.

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

                                  Type of update operation to perform.

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

                                  Type of update operation to perform.

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

                                  Data to update as a list of records.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + /** + *

                                  Data to update as a list of records.

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

                                  Data to update as a list of records.

                                  + */ + @java.lang.Override + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public _FinalStage records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + @java.lang.Override + public UpdateRequest build() { + return new UpdateRequest(vaultId, tableName, records, updateType, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordByIdRequestRedaction.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordByIdRequestRedaction.java new file mode 100644 index 00000000..46191987 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordByIdRequestRedaction.java @@ -0,0 +1,108 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class GetRecordByIdRequestRedaction { + public static final GetRecordByIdRequestRedaction DEFAULT = + new GetRecordByIdRequestRedaction(Value.DEFAULT, "DEFAULT"); + + public static final GetRecordByIdRequestRedaction PLAIN_TEXT = + new GetRecordByIdRequestRedaction(Value.PLAIN_TEXT, "PLAIN_TEXT"); + + public static final GetRecordByIdRequestRedaction MASKED = + new GetRecordByIdRequestRedaction(Value.MASKED, "MASKED"); + + public static final GetRecordByIdRequestRedaction REDACTED = + new GetRecordByIdRequestRedaction(Value.REDACTED, "REDACTED"); + + private final Value value; + + private final String string; + + GetRecordByIdRequestRedaction(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof GetRecordByIdRequestRedaction + && this.string.equals(((GetRecordByIdRequestRedaction) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case DEFAULT: + return visitor.visitDefault(); + case PLAIN_TEXT: + return visitor.visitPlainText(); + case MASKED: + return visitor.visitMasked(); + case REDACTED: + return visitor.visitRedacted(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static GetRecordByIdRequestRedaction valueOf(String value) { + switch (value) { + case "DEFAULT": + return DEFAULT; + case "PLAIN_TEXT": + return PLAIN_TEXT; + case "MASKED": + return MASKED; + case "REDACTED": + return REDACTED; + default: + return new GetRecordByIdRequestRedaction(Value.UNKNOWN, value); + } + } + + public enum Value { + DEFAULT, + + REDACTED, + + MASKED, + + PLAIN_TEXT, + + UNKNOWN + } + + public interface Visitor { + T visitDefault(); + + T visitRedacted(); + + T visitMasked(); + + T visitPlainText(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordsRequestOrderBy.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordsRequestOrderBy.java new file mode 100644 index 00000000..886afd43 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordsRequestOrderBy.java @@ -0,0 +1,95 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class GetRecordsRequestOrderBy { + public static final GetRecordsRequestOrderBy DESCENDING = + new GetRecordsRequestOrderBy(Value.DESCENDING, "DESCENDING"); + + public static final GetRecordsRequestOrderBy NONE = new GetRecordsRequestOrderBy(Value.NONE, "NONE"); + + public static final GetRecordsRequestOrderBy ASCENDING = new GetRecordsRequestOrderBy(Value.ASCENDING, "ASCENDING"); + + private final Value value; + + private final String string; + + GetRecordsRequestOrderBy(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof GetRecordsRequestOrderBy + && this.string.equals(((GetRecordsRequestOrderBy) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case DESCENDING: + return visitor.visitDescending(); + case NONE: + return visitor.visitNone(); + case ASCENDING: + return visitor.visitAscending(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static GetRecordsRequestOrderBy valueOf(String value) { + switch (value) { + case "DESCENDING": + return DESCENDING; + case "NONE": + return NONE; + case "ASCENDING": + return ASCENDING; + default: + return new GetRecordsRequestOrderBy(Value.UNKNOWN, value); + } + } + + public enum Value { + ASCENDING, + + DESCENDING, + + NONE, + + UNKNOWN + } + + public interface Visitor { + T visitAscending(); + + T visitDescending(); + + T visitNone(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordsRequestRedaction.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordsRequestRedaction.java new file mode 100644 index 00000000..f3ac934c --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/GetRecordsRequestRedaction.java @@ -0,0 +1,106 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class GetRecordsRequestRedaction { + public static final GetRecordsRequestRedaction DEFAULT = new GetRecordsRequestRedaction(Value.DEFAULT, "DEFAULT"); + + public static final GetRecordsRequestRedaction PLAIN_TEXT = + new GetRecordsRequestRedaction(Value.PLAIN_TEXT, "PLAIN_TEXT"); + + public static final GetRecordsRequestRedaction MASKED = new GetRecordsRequestRedaction(Value.MASKED, "MASKED"); + + public static final GetRecordsRequestRedaction REDACTED = + new GetRecordsRequestRedaction(Value.REDACTED, "REDACTED"); + + private final Value value; + + private final String string; + + GetRecordsRequestRedaction(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof GetRecordsRequestRedaction + && this.string.equals(((GetRecordsRequestRedaction) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case DEFAULT: + return visitor.visitDefault(); + case PLAIN_TEXT: + return visitor.visitPlainText(); + case MASKED: + return visitor.visitMasked(); + case REDACTED: + return visitor.visitRedacted(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static GetRecordsRequestRedaction valueOf(String value) { + switch (value) { + case "DEFAULT": + return DEFAULT; + case "PLAIN_TEXT": + return PLAIN_TEXT; + case "MASKED": + return MASKED; + case "REDACTED": + return REDACTED; + default: + return new GetRecordsRequestRedaction(Value.UNKNOWN, value); + } + } + + public enum Value { + DEFAULT, + + REDACTED, + + MASKED, + + PLAIN_TEXT, + + UNKNOWN + } + + public interface Visitor { + T visitDefault(); + + T visitRedacted(); + + T visitMasked(); + + T visitPlainText(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/InsertRecordRequestByot.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/InsertRecordRequestByot.java new file mode 100644 index 00000000..b4e402aa --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/InsertRecordRequestByot.java @@ -0,0 +1,95 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class InsertRecordRequestByot { + public static final InsertRecordRequestByot ENABLE_STRICT = + new InsertRecordRequestByot(Value.ENABLE_STRICT, "ENABLE_STRICT"); + + public static final InsertRecordRequestByot DISABLE = new InsertRecordRequestByot(Value.DISABLE, "DISABLE"); + + public static final InsertRecordRequestByot ENABLE = new InsertRecordRequestByot(Value.ENABLE, "ENABLE"); + + private final Value value; + + private final String string; + + InsertRecordRequestByot(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof InsertRecordRequestByot + && this.string.equals(((InsertRecordRequestByot) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ENABLE_STRICT: + return visitor.visitEnableStrict(); + case DISABLE: + return visitor.visitDisable(); + case ENABLE: + return visitor.visitEnable(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static InsertRecordRequestByot valueOf(String value) { + switch (value) { + case "ENABLE_STRICT": + return ENABLE_STRICT; + case "DISABLE": + return DISABLE; + case "ENABLE": + return ENABLE; + default: + return new InsertRecordRequestByot(Value.UNKNOWN, value); + } + } + + public enum Value { + DISABLE, + + ENABLE, + + ENABLE_STRICT, + + UNKNOWN + } + + public interface Visitor { + T visitDisable(); + + T visitEnable(); + + T visitEnableStrict(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestOrderBy.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestOrderBy.java deleted file mode 100644 index 1f25b38d..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestOrderBy.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.records.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum RecordServiceBulkGetRecordRequestOrderBy { - ASCENDING("ASCENDING"), - - DESCENDING("DESCENDING"), - - NONE("NONE"); - - private final String value; - - RecordServiceBulkGetRecordRequestOrderBy(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestRedaction.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestRedaction.java deleted file mode 100644 index 12bbc291..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestRedaction.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.records.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum RecordServiceBulkGetRecordRequestRedaction { - DEFAULT("DEFAULT"), - - REDACTED("REDACTED"), - - MASKED("MASKED"), - - PLAIN_TEXT("PLAIN_TEXT"); - - private final String value; - - RecordServiceBulkGetRecordRequestRedaction(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceGetRecordRequestRedaction.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceGetRecordRequestRedaction.java deleted file mode 100644 index 4f546262..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceGetRecordRequestRedaction.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.records.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum RecordServiceGetRecordRequestRedaction { - DEFAULT("DEFAULT"), - - REDACTED("REDACTED"), - - MASKED("MASKED"), - - PLAIN_TEXT("PLAIN_TEXT"); - - private final String value; - - RecordServiceGetRecordRequestRedaction(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/UpdateRecordRequestByot.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/UpdateRecordRequestByot.java new file mode 100644 index 00000000..6af77d59 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/UpdateRecordRequestByot.java @@ -0,0 +1,95 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class UpdateRecordRequestByot { + public static final UpdateRecordRequestByot ENABLE_STRICT = + new UpdateRecordRequestByot(Value.ENABLE_STRICT, "ENABLE_STRICT"); + + public static final UpdateRecordRequestByot DISABLE = new UpdateRecordRequestByot(Value.DISABLE, "DISABLE"); + + public static final UpdateRecordRequestByot ENABLE = new UpdateRecordRequestByot(Value.ENABLE, "ENABLE"); + + private final Value value; + + private final String string; + + UpdateRecordRequestByot(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof UpdateRecordRequestByot + && this.string.equals(((UpdateRecordRequestByot) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ENABLE_STRICT: + return visitor.visitEnableStrict(); + case DISABLE: + return visitor.visitDisable(); + case ENABLE: + return visitor.visitEnable(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static UpdateRecordRequestByot valueOf(String value) { + switch (value) { + case "ENABLE_STRICT": + return ENABLE_STRICT; + case "DISABLE": + return DISABLE; + case "ENABLE": + return ENABLE; + default: + return new UpdateRecordRequestByot(Value.UNKNOWN, value); + } + } + + public enum Value { + DISABLE, + + ENABLE, + + ENABLE_STRICT, + + UNKNOWN + } + + public interface Visitor { + T visitDisable(); + + T visitEnable(); + + T visitEnableStrict(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/UpdateRequestUpdateType.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/UpdateRequestUpdateType.java new file mode 100644 index 00000000..660067b8 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/records/types/UpdateRequestUpdateType.java @@ -0,0 +1,84 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class UpdateRequestUpdateType { + public static final UpdateRequestUpdateType REPLACE = new UpdateRequestUpdateType(Value.REPLACE, "REPLACE"); + + public static final UpdateRequestUpdateType UPDATE = new UpdateRequestUpdateType(Value.UPDATE, "UPDATE"); + + private final Value value; + + private final String string; + + UpdateRequestUpdateType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof UpdateRequestUpdateType + && this.string.equals(((UpdateRequestUpdateType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case REPLACE: + return visitor.visitReplace(); + case UPDATE: + return visitor.visitUpdate(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static UpdateRequestUpdateType valueOf(String value) { + switch (value) { + case "REPLACE": + return REPLACE; + case "UPDATE": + return UPDATE; + default: + return new UpdateRequestUpdateType(Value.UNKNOWN, value); + } + } + + public enum Value { + UPDATE, + + REPLACE, + + UNKNOWN + } + + public interface Visitor { + T visitUpdate(); + + T visitReplace(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncStringsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncStringsClient.java deleted file mode 100644 index 66ef72c5..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncStringsClient.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.strings; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; -import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; -import com.skyflow.generated.rest.types.DeidentifyStringResponse; -import com.skyflow.generated.rest.types.IdentifyResponse; - -import java.util.concurrent.CompletableFuture; - -public class AsyncStringsClient { - protected final ClientOptions clientOptions; - - private final AsyncRawStringsClient rawClient; - - public AsyncStringsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawStringsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawStringsClient withRawResponse() { - return this.rawClient; - } - - /** - * De-identifies sensitive data from a string. - */ - public CompletableFuture deidentifyString(DeidentifyStringRequest request) { - return this.rawClient.deidentifyString(request).thenApply(response -> response.body()); - } - - /** - * De-identifies sensitive data from a string. - */ - public CompletableFuture deidentifyString( - DeidentifyStringRequest request, RequestOptions requestOptions) { - return this.rawClient.deidentifyString(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Re-identifies tokens in a string. - */ - public CompletableFuture reidentifyString() { - return this.rawClient.reidentifyString().thenApply(response -> response.body()); - } - - /** - * Re-identifies tokens in a string. - */ - public CompletableFuture reidentifyString(ReidentifyStringRequest request) { - return this.rawClient.reidentifyString(request).thenApply(response -> response.body()); - } - - /** - * Re-identifies tokens in a string. - */ - public CompletableFuture reidentifyString( - ReidentifyStringRequest request, RequestOptions requestOptions) { - return this.rawClient.reidentifyString(request, requestOptions).thenApply(response -> response.body()); - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/RawStringsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/RawStringsClient.java deleted file mode 100644 index da6bec56..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/RawStringsClient.java +++ /dev/null @@ -1,166 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.strings; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; -import com.skyflow.generated.rest.errors.BadRequestError; -import com.skyflow.generated.rest.errors.InternalServerError; -import com.skyflow.generated.rest.errors.UnauthorizedError; -import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; -import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; -import com.skyflow.generated.rest.types.DeidentifyStringResponse; -import com.skyflow.generated.rest.types.ErrorResponse; -import com.skyflow.generated.rest.types.IdentifyResponse; -import okhttp3.*; - -import java.io.IOException; - -public class RawStringsClient { - protected final ClientOptions clientOptions; - - public RawStringsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * De-identifies sensitive data from a string. - */ - public ApiClientHttpResponse deidentifyString(DeidentifyStringRequest request) { - return deidentifyString(request, null); - } - - /** - * De-identifies sensitive data from a string. - */ - public ApiClientHttpResponse deidentifyString( - DeidentifyStringRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/deidentify/string") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyStringResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * Re-identifies tokens in a string. - */ - public ApiClientHttpResponse reidentifyString() { - return reidentifyString(ReidentifyStringRequest.builder().build()); - } - - /** - * Re-identifies tokens in a string. - */ - public ApiClientHttpResponse reidentifyString(ReidentifyStringRequest request) { - return reidentifyString(request, null); - } - - /** - * Re-identifies tokens in a string. - */ - public ApiClientHttpResponse reidentifyString( - ReidentifyStringRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/reidentify/string") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), IdentifyResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/StringsClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/StringsClient.java deleted file mode 100644 index 5dfca68b..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/StringsClient.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.strings; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; -import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; -import com.skyflow.generated.rest.types.DeidentifyStringResponse; -import com.skyflow.generated.rest.types.IdentifyResponse; - -public class StringsClient { - protected final ClientOptions clientOptions; - - private final RawStringsClient rawClient; - - public StringsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new RawStringsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawStringsClient withRawResponse() { - return this.rawClient; - } - - /** - * De-identifies sensitive data from a string. - */ - public DeidentifyStringResponse deidentifyString(DeidentifyStringRequest request) { - return this.rawClient.deidentifyString(request).body(); - } - - /** - * De-identifies sensitive data from a string. - */ - public DeidentifyStringResponse deidentifyString(DeidentifyStringRequest request, RequestOptions requestOptions) { - return this.rawClient.deidentifyString(request, requestOptions).body(); - } - - /** - * Re-identifies tokens in a string. - */ - public IdentifyResponse reidentifyString() { - return this.rawClient.reidentifyString().body(); - } - - /** - * Re-identifies tokens in a string. - */ - public IdentifyResponse reidentifyString(ReidentifyStringRequest request) { - return this.rawClient.reidentifyString(request).body(); - } - - /** - * Re-identifies tokens in a string. - */ - public IdentifyResponse reidentifyString(ReidentifyStringRequest request, RequestOptions requestOptions) { - return this.rawClient.reidentifyString(request, requestOptions).body(); - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java deleted file mode 100644 index 06ec6cec..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java +++ /dev/null @@ -1,394 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.strings.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.resources.strings.types.DeidentifyStringRequestEntityTypesItem; -import com.skyflow.generated.rest.types.TokenTypeMapping; -import com.skyflow.generated.rest.types.Transformations; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyStringRequest.Builder.class) -public final class DeidentifyStringRequest { - private final String text; - - private final String vaultId; - - private final Optional> entityTypes; - - private final Optional tokenType; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional transformations; - - private final Optional configurationId; - - private final Map additionalProperties; - - private DeidentifyStringRequest( - String text, - String vaultId, - Optional> entityTypes, - Optional tokenType, - Optional> allowRegex, - Optional> restrictRegex, - Optional transformations, - Optional configurationId, - Map additionalProperties) { - this.text = text; - this.vaultId = vaultId; - this.entityTypes = entityTypes; - this.tokenType = tokenType; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.transformations = transformations; - this.configurationId = configurationId; - this.additionalProperties = additionalProperties; - } - - /** - * @return Text to de-identify. - */ - @JsonProperty("text") - public String getText() { - return text; - } - - /** - * @return ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Entities to detect and de-identify. - */ - @JsonProperty("entity_types") - public Optional> getEntityTypes() { - return entityTypes; - } - - @JsonProperty("token_type") - public Optional getTokenType() { - return tokenType; - } - - /** - * @return Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - @JsonProperty("transformations") - public Optional getTransformations() { - return transformations; - } - - /** - * @return ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file. - */ - @JsonProperty("configuration_id") - public Optional getConfigurationId() { - return configurationId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyStringRequest && equalTo((DeidentifyStringRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyStringRequest other) { - return text.equals(other.text) - && vaultId.equals(other.vaultId) - && entityTypes.equals(other.entityTypes) - && tokenType.equals(other.tokenType) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && transformations.equals(other.transformations) - && configurationId.equals(other.configurationId); - } - - @Override - public int hashCode() { - return Objects.hash( - this.text, - this.vaultId, - this.entityTypes, - this.tokenType, - this.allowRegex, - this.restrictRegex, - this.transformations, - this.configurationId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static TextStage builder() { - return new Builder(); - } - - public interface TextStage { - /** - * Text to de-identify. - */ - VaultIdStage text(@NotNull String text); - - Builder from(DeidentifyStringRequest other); - } - - public interface VaultIdStage { - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DeidentifyStringRequest build(); - - /** - *

                                  Entities to detect and de-identify.

                                  - */ - _FinalStage entityTypes(Optional> entityTypes); - - _FinalStage entityTypes(List entityTypes); - - _FinalStage tokenType(Optional tokenType); - - _FinalStage tokenType(TokenTypeMapping tokenType); - - /** - *

                                  Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

                                  Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

                                  ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

                                  - */ - _FinalStage configurationId(Optional configurationId); - - _FinalStage configurationId(String configurationId); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements TextStage, VaultIdStage, _FinalStage { - private String text; - - private String vaultId; - - private Optional configurationId = Optional.empty(); - - private Optional transformations = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional tokenType = Optional.empty(); - - private Optional> entityTypes = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(DeidentifyStringRequest other) { - text(other.getText()); - vaultId(other.getVaultId()); - entityTypes(other.getEntityTypes()); - tokenType(other.getTokenType()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - transformations(other.getTransformations()); - configurationId(other.getConfigurationId()); - return this; - } - - /** - * Text to de-identify.

                                  Text to de-identify.

                                  - * @return Reference to {@code this} so that method calls can be chained together. - */ - @Override - @JsonSetter("text") - public VaultIdStage text(@NotNull String text) { - this.text = Objects.requireNonNull(text, "text must not be null"); - return this; - } - - /** - * ID of a vault that you have Detect Invoker or Vault Owner permissions for.

                                  ID of a vault that you have Detect Invoker or Vault Owner permissions for.

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

                                  ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

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

                                  ID of the Detect configuration to use for de-identification. Can't be specified with fields other than vault_id, text, and file.

                                  - */ - @Override - @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) - public _FinalStage configurationId(Optional configurationId) { - this.configurationId = configurationId; - return this; - } - - @Override - public _FinalStage transformations(Transformations transformations) { - this.transformations = Optional.ofNullable(transformations); - return this; - } - - @Override - @JsonSetter(value = "transformations", nulls = Nulls.SKIP) - public _FinalStage transformations(Optional transformations) { - this.transformations = transformations; - return this; - } - - /** - *

                                  Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

                                  Regular expressions to replace with '[RESTRICTED]'. Expressions must match the entirety of a detected entity, not just a substring, for the entity to be restricted. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext. If a string is detected as an entity and a restrict_regex pattern matches the entire detected entity, the entity is replaced with '[RESTRICTED]'. If a string is detected as an entity but a restrict_regex pattern only matches a substring of it, the restrict_regex pattern is ignored, and the entity is processed according to the specified tokenization and transformation settings.

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

                                  Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

                                  Regular expressions to display in plaintext. Entities appear in plaintext if an expression matches either the entirety of a detected entity or a substring of it. Expressions don't match across entity boundaries. If a string or entity matches both allow_regex and restrict_regex, the entity is displayed in plaintext.

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

                                  Entities to detect and de-identify.

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

                                  Entities to detect and de-identify.

                                  - */ - @Override - @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) - public _FinalStage entityTypes(Optional> entityTypes) { - this.entityTypes = entityTypes; - return this; - } - - @Override - public DeidentifyStringRequest build() { - return new DeidentifyStringRequest( - text, - vaultId, - entityTypes, - tokenType, - allowRegex, - restrictRegex, - transformations, - configurationId, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/requests/ReidentifyStringRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/requests/ReidentifyStringRequest.java deleted file mode 100644 index 3c42390c..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/requests/ReidentifyStringRequest.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.strings.requests; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.types.Format; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = ReidentifyStringRequest.Builder.class) -public final class ReidentifyStringRequest { - private final Optional text; - - private final Optional vaultId; - - private final Optional format; - - private final Map additionalProperties; - - private ReidentifyStringRequest( - Optional text, - Optional vaultId, - Optional format, - Map additionalProperties) { - this.text = text; - this.vaultId = vaultId; - this.format = format; - this.additionalProperties = additionalProperties; - } - - /** - * @return Text to reidentify. - */ - @JsonProperty("text") - public Optional getText() { - return text; - } - - /** - * @return ID of the vault where the entities are stored. - */ - @JsonProperty("vault_id") - public Optional getVaultId() { - return vaultId; - } - - @JsonProperty("format") - public Optional getFormat() { - return format; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof ReidentifyStringRequest && equalTo((ReidentifyStringRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(ReidentifyStringRequest other) { - return text.equals(other.text) && vaultId.equals(other.vaultId) && format.equals(other.format); - } - - @Override - public int hashCode() { - return Objects.hash(this.text, this.vaultId, this.format); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional text = Optional.empty(); - - private Optional vaultId = Optional.empty(); - - private Optional format = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(ReidentifyStringRequest other) { - text(other.getText()); - vaultId(other.getVaultId()); - format(other.getFormat()); - return this; - } - - /** - *

                                  Text to reidentify.

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

                                  ID of the vault where the entities are stored.

                                  - */ - @JsonSetter(value = "vault_id", nulls = Nulls.SKIP) - public Builder vaultId(Optional vaultId) { - this.vaultId = vaultId; - return this; - } - - public Builder vaultId(String vaultId) { - this.vaultId = Optional.ofNullable(vaultId); - return this; - } - - @JsonSetter(value = "format", nulls = Nulls.SKIP) - public Builder format(Optional format) { - this.format = format; - return this; - } - - public Builder format(Format format) { - this.format = Optional.ofNullable(format); - return this; - } - - public ReidentifyStringRequest build() { - return new ReidentifyStringRequest(text, vaultId, format, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/types/DeidentifyStringRequestEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/types/DeidentifyStringRequestEntityTypesItem.java deleted file mode 100644 index 28066122..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/strings/types/DeidentifyStringRequestEntityTypesItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.strings.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifyStringRequestEntityTypesItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - DeidentifyStringRequestEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncRawTokensClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncRawTokensClient.java index 794035bd..5543aadc 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncRawTokensClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncRawTokensClient.java @@ -4,17 +4,35 @@ package com.skyflow.generated.rest.resources.tokens; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; -import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; -import com.skyflow.generated.rest.types.V1DetokenizeResponse; -import com.skyflow.generated.rest.types.V1TokenizeResponse; -import okhttp3.*; -import org.jetbrains.annotations.NotNull; - +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.tokens.requests.DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.TokenizePayload; +import com.skyflow.generated.rest.types.DetokenizeResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.TokenizeResponse; import java.io.IOException; import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; public class AsyncRawTokensClient { protected final ClientOptions clientOptions; @@ -26,29 +44,26 @@ public AsyncRawTokensClient(ClientOptions clientOptions) { /** * Returns records that correspond to the specified tokens. */ - public CompletableFuture> recordServiceDetokenize(String vaultId) { - return recordServiceDetokenize(vaultId, V1DetokenizePayload.builder().build()); + public CompletableFuture> detokenize( + String vaultId, DetokenizePayload request) { + return detokenize(vaultId, request, null); } /** * Returns records that correspond to the specified tokens. */ - public CompletableFuture> recordServiceDetokenize( - String vaultId, V1DetokenizePayload request) { - return recordServiceDetokenize(vaultId, request, null); - } - - /** - * Returns records that correspond to the specified tokens. - */ - public CompletableFuture> recordServiceDetokenize( - String vaultId, V1DetokenizePayload request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> detokenize( + String vaultId, DetokenizePayload request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegments("detokenize") - .build(); + .addPathSegments("detokenize"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -57,7 +72,7 @@ public CompletableFuture> recordServ throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -67,33 +82,60 @@ public CompletableFuture> recordServ if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetokenizeResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DetokenizeResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } @@ -108,31 +150,28 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { } /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. - */ - public CompletableFuture> recordServiceTokenize(String vaultId) { - return recordServiceTokenize(vaultId, V1TokenizePayload.builder().build()); - } - - /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and return tokens for that new record's values, see Insert Records' tokenization parameter. */ - public CompletableFuture> recordServiceTokenize( - String vaultId, V1TokenizePayload request) { - return recordServiceTokenize(vaultId, request, null); + public CompletableFuture> tokenize( + String vaultId, TokenizePayload request) { + return tokenize(vaultId, request, null); } /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and return tokens for that new record's values, see Insert Records' tokenization parameter. */ - public CompletableFuture> recordServiceTokenize( - String vaultId, V1TokenizePayload request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public CompletableFuture> tokenize( + String vaultId, TokenizePayload request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegments("tokenize") - .build(); + .addPathSegments("tokenize"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -141,7 +180,7 @@ public CompletableFuture> recordServic throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -151,33 +190,60 @@ public CompletableFuture> recordServic if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } - CompletableFuture> future = new CompletableFuture<>(); + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } + CompletableFuture> future = new CompletableFuture<>(); client.newCall(okhttpRequest).enqueue(new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1TokenizeResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, TokenizeResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; + } catch (JsonProcessingException e) { + future.completeExceptionally( + new ApiClientException("Failed to deserialize response: " + e.getMessage(), e)); } catch (IOException e) { future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncTokensClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncTokensClient.java index 621701af..da6a88de 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncTokensClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncTokensClient.java @@ -5,11 +5,10 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; -import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; -import com.skyflow.generated.rest.types.V1DetokenizeResponse; -import com.skyflow.generated.rest.types.V1TokenizeResponse; - +import com.skyflow.generated.rest.resources.tokens.requests.DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.TokenizePayload; +import com.skyflow.generated.rest.types.DetokenizeResponse; +import com.skyflow.generated.rest.types.TokenizeResponse; import java.util.concurrent.CompletableFuture; public class AsyncTokensClient { @@ -32,49 +31,30 @@ public AsyncRawTokensClient withRawResponse() { /** * Returns records that correspond to the specified tokens. */ - public CompletableFuture recordServiceDetokenize(String vaultId) { - return this.rawClient.recordServiceDetokenize(vaultId).thenApply(response -> response.body()); - } - - /** - * Returns records that correspond to the specified tokens. - */ - public CompletableFuture recordServiceDetokenize( - String vaultId, V1DetokenizePayload request) { - return this.rawClient.recordServiceDetokenize(vaultId, request).thenApply(response -> response.body()); + public CompletableFuture detokenize(String vaultId, DetokenizePayload request) { + return this.rawClient.detokenize(vaultId, request).thenApply(response -> response.body()); } /** * Returns records that correspond to the specified tokens. */ - public CompletableFuture recordServiceDetokenize( - String vaultId, V1DetokenizePayload request, RequestOptions requestOptions) { - return this.rawClient - .recordServiceDetokenize(vaultId, request, requestOptions) - .thenApply(response -> response.body()); - } - - /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. - */ - public CompletableFuture recordServiceTokenize(String vaultId) { - return this.rawClient.recordServiceTokenize(vaultId).thenApply(response -> response.body()); + public CompletableFuture detokenize( + String vaultId, DetokenizePayload request, RequestOptions requestOptions) { + return this.rawClient.detokenize(vaultId, request, requestOptions).thenApply(response -> response.body()); } /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and return tokens for that new record's values, see Insert Records' tokenization parameter. */ - public CompletableFuture recordServiceTokenize(String vaultId, V1TokenizePayload request) { - return this.rawClient.recordServiceTokenize(vaultId, request).thenApply(response -> response.body()); + public CompletableFuture tokenize(String vaultId, TokenizePayload request) { + return this.rawClient.tokenize(vaultId, request).thenApply(response -> response.body()); } /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and return tokens for that new record's values, see Insert Records' tokenization parameter. */ - public CompletableFuture recordServiceTokenize( - String vaultId, V1TokenizePayload request, RequestOptions requestOptions) { - return this.rawClient - .recordServiceTokenize(vaultId, request, requestOptions) - .thenApply(response -> response.body()); + public CompletableFuture tokenize( + String vaultId, TokenizePayload request, RequestOptions requestOptions) { + return this.rawClient.tokenize(vaultId, request, requestOptions).thenApply(response -> response.body()); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/RawTokensClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/RawTokensClient.java index 7ad69d11..6780c88c 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/RawTokensClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/RawTokensClient.java @@ -4,15 +4,31 @@ package com.skyflow.generated.rest.resources.tokens; import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.*; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.core.RetryInterceptor; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; -import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; -import com.skyflow.generated.rest.types.V1DetokenizeResponse; -import com.skyflow.generated.rest.types.V1TokenizeResponse; -import okhttp3.*; - +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.tokens.requests.DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.TokenizePayload; +import com.skyflow.generated.rest.types.DetokenizeResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.TokenizeResponse; import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class RawTokensClient { protected final ClientOptions clientOptions; @@ -24,29 +40,25 @@ public RawTokensClient(ClientOptions clientOptions) { /** * Returns records that correspond to the specified tokens. */ - public ApiClientHttpResponse recordServiceDetokenize(String vaultId) { - return recordServiceDetokenize(vaultId, V1DetokenizePayload.builder().build()); - } - - /** - * Returns records that correspond to the specified tokens. - */ - public ApiClientHttpResponse recordServiceDetokenize( - String vaultId, V1DetokenizePayload request) { - return recordServiceDetokenize(vaultId, request, null); + public ApiClientHttpResponse detokenize(String vaultId, DetokenizePayload request) { + return detokenize(vaultId, request, null); } /** * Returns records that correspond to the specified tokens. */ - public ApiClientHttpResponse recordServiceDetokenize( - String vaultId, V1DetokenizePayload request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse detokenize( + String vaultId, DetokenizePayload request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegments("detokenize") - .build(); + .addPathSegments("detokenize"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -55,7 +67,7 @@ public ApiClientHttpResponse recordServiceDetokenize( throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -65,57 +77,72 @@ public ApiClientHttpResponse recordServiceDetokenize( if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetokenizeResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DetokenizeResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } } /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. - */ - public ApiClientHttpResponse recordServiceTokenize(String vaultId) { - return recordServiceTokenize(vaultId, V1TokenizePayload.builder().build()); - } - - /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and return tokens for that new record's values, see Insert Records' tokenization parameter. */ - public ApiClientHttpResponse recordServiceTokenize(String vaultId, V1TokenizePayload request) { - return recordServiceTokenize(vaultId, request, null); + public ApiClientHttpResponse tokenize(String vaultId, TokenizePayload request) { + return tokenize(vaultId, request, null); } /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and return tokens for that new record's values, see Insert Records' tokenization parameter. */ - public ApiClientHttpResponse recordServiceTokenize( - String vaultId, V1TokenizePayload request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + public ApiClientHttpResponse tokenize( + String vaultId, TokenizePayload request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) .newBuilder() .addPathSegments("v1/vaults") .addPathSegment(vaultId) - .addPathSegments("tokenize") - .build(); + .addPathSegments("tokenize"); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + }); + } RequestBody body; try { body = RequestBody.create( @@ -124,7 +151,7 @@ public ApiClientHttpResponse recordServiceTokenize( throw new ApiClientException("Failed to serialize request", e); } Request okhttpRequest = new Request.Builder() - .url(httpUrl) + .url(httpUrl.build()) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") @@ -134,26 +161,45 @@ public ApiClientHttpResponse recordServiceTokenize( if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } + if (requestOptions != null && requestOptions.getMaxRetries().isPresent()) { + okhttpRequest = okhttpRequest + .newBuilder() + .tag( + RetryInterceptor.MaxRetriesOverride.class, + new RetryInterceptor.MaxRetriesOverride( + requestOptions.getMaxRetries().get())) + .build(); + } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1TokenizeResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, TokenizeResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); } } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to deserialize response: " + e.getMessage(), e); } catch (IOException e) { throw new ApiClientException("Network error executing HTTP request", e); } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/TokensClient.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/TokensClient.java index 8b0e7e40..47656ee5 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/TokensClient.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/TokensClient.java @@ -5,10 +5,10 @@ import com.skyflow.generated.rest.core.ClientOptions; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; -import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; -import com.skyflow.generated.rest.types.V1DetokenizeResponse; -import com.skyflow.generated.rest.types.V1TokenizeResponse; +import com.skyflow.generated.rest.resources.tokens.requests.DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.TokenizePayload; +import com.skyflow.generated.rest.types.DetokenizeResponse; +import com.skyflow.generated.rest.types.TokenizeResponse; public class TokensClient { protected final ClientOptions clientOptions; @@ -30,48 +30,28 @@ public RawTokensClient withRawResponse() { /** * Returns records that correspond to the specified tokens. */ - public V1DetokenizeResponse recordServiceDetokenize(String vaultId) { - return this.rawClient.recordServiceDetokenize(vaultId).body(); + public DetokenizeResponse detokenize(String vaultId, DetokenizePayload request) { + return this.rawClient.detokenize(vaultId, request).body(); } /** * Returns records that correspond to the specified tokens. */ - public V1DetokenizeResponse recordServiceDetokenize(String vaultId, V1DetokenizePayload request) { - return this.rawClient.recordServiceDetokenize(vaultId, request).body(); + public DetokenizeResponse detokenize(String vaultId, DetokenizePayload request, RequestOptions requestOptions) { + return this.rawClient.detokenize(vaultId, request, requestOptions).body(); } /** - * Returns records that correspond to the specified tokens. - */ - public V1DetokenizeResponse recordServiceDetokenize( - String vaultId, V1DetokenizePayload request, RequestOptions requestOptions) { - return this.rawClient - .recordServiceDetokenize(vaultId, request, requestOptions) - .body(); - } - - /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. - */ - public V1TokenizeResponse recordServiceTokenize(String vaultId) { - return this.rawClient.recordServiceTokenize(vaultId).body(); - } - - /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and return tokens for that new record's values, see Insert Records' tokenization parameter. */ - public V1TokenizeResponse recordServiceTokenize(String vaultId, V1TokenizePayload request) { - return this.rawClient.recordServiceTokenize(vaultId, request).body(); + public TokenizeResponse tokenize(String vaultId, TokenizePayload request) { + return this.rawClient.tokenize(vaultId, request).body(); } /** - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.Note: This endpoint doesn't insert records—it returns tokens for existing values. To insert records and return tokens for that new record's values, see Insert Records' tokenization parameter. */ - public V1TokenizeResponse recordServiceTokenize( - String vaultId, V1TokenizePayload request, RequestOptions requestOptions) { - return this.rawClient - .recordServiceTokenize(vaultId, request, requestOptions) - .body(); + public TokenizeResponse tokenize(String vaultId, TokenizePayload request, RequestOptions requestOptions) { + return this.rawClient.tokenize(vaultId, request, requestOptions).body(); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DeleteTokenRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DeleteTokenRequest.java new file mode 100644 index 00000000..61f59fa4 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DeleteTokenRequest.java @@ -0,0 +1,189 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeleteTokenRequest.Builder.class) +public final class DeleteTokenRequest { + private final String vaultId; + + private final List tokens; + + private final Map additionalProperties; + + private DeleteTokenRequest(String vaultId, List tokens, Map additionalProperties) { + this.vaultId = vaultId; + this.tokens = tokens; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Tokens to delete. + */ + @JsonProperty("tokens") + public List getTokens() { + return tokens; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeleteTokenRequest && equalTo((DeleteTokenRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeleteTokenRequest other) { + return vaultId.equals(other.vaultId) && tokens.equals(other.tokens); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.tokens); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault.

                                  + */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(DeleteTokenRequest other); + } + + public interface _FinalStage { + DeleteTokenRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Tokens to delete.

                                  + */ + _FinalStage tokens(List tokens); + + _FinalStage addTokens(String tokens); + + _FinalStage addAllTokens(List tokens); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private List tokens = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeleteTokenRequest other) { + vaultId(other.getVaultId()); + tokens(other.getTokens()); + return this; + } + + /** + *

                                  ID of the vault.

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

                                  Tokens to delete.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllTokens(List tokens) { + if (tokens != null) { + this.tokens.addAll(tokens); + } + return this; + } + + /** + *

                                  Tokens to delete.

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

                                  Tokens to delete.

                                  + */ + @java.lang.Override + @JsonSetter(value = "tokens", nulls = Nulls.SKIP) + public _FinalStage tokens(List tokens) { + this.tokens.clear(); + if (tokens != null) { + this.tokens.addAll(tokens); + } + return this; + } + + @java.lang.Override + public DeleteTokenRequest build() { + return new DeleteTokenRequest(vaultId, tokens, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1DetokenizePayload.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DetokenizePayload.java similarity index 61% rename from skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1DetokenizePayload.java rename to skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DetokenizePayload.java index 52571f64..03681bb5 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1DetokenizePayload.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DetokenizePayload.java @@ -3,17 +3,27 @@ */ package com.skyflow.generated.rest.resources.tokens.requests; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.types.V1DetokenizeRecordRequest; - -import java.util.*; +import com.skyflow.generated.rest.types.DetokenizeRecordRequest; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1DetokenizePayload.Builder.class) -public final class V1DetokenizePayload { - private final Optional> detokenizationParameters; +@JsonDeserialize(builder = DetokenizePayload.Builder.class) +public final class DetokenizePayload { + private final List detokenizationParameters; private final Optional downloadUrl; @@ -21,8 +31,8 @@ public final class V1DetokenizePayload { private final Map additionalProperties; - private V1DetokenizePayload( - Optional> detokenizationParameters, + private DetokenizePayload( + List detokenizationParameters, Optional downloadUrl, Optional continueOnError, Map additionalProperties) { @@ -36,7 +46,7 @@ private V1DetokenizePayload( * @return Detokenization details. */ @JsonProperty("detokenizationParameters") - public Optional> getDetokenizationParameters() { + public List getDetokenizationParameters() { return detokenizationParameters; } @@ -56,10 +66,10 @@ public Optional getContinueOnError() { return continueOnError; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof V1DetokenizePayload && equalTo((V1DetokenizePayload) other); + return other instanceof DetokenizePayload && equalTo((DetokenizePayload) other); } @JsonAnyGetter @@ -67,18 +77,18 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(V1DetokenizePayload other) { + private boolean equalTo(DetokenizePayload other) { return detokenizationParameters.equals(other.detokenizationParameters) && downloadUrl.equals(other.downloadUrl) && continueOnError.equals(other.continueOnError); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.detokenizationParameters, this.downloadUrl, this.continueOnError); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -89,7 +99,7 @@ public static Builder builder() { @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder { - private Optional> detokenizationParameters = Optional.empty(); + private List detokenizationParameters = new ArrayList<>(); private Optional downloadUrl = Optional.empty(); @@ -100,7 +110,7 @@ public static final class Builder { private Builder() {} - public Builder from(V1DetokenizePayload other) { + public Builder from(DetokenizePayload other) { detokenizationParameters(other.getDetokenizationParameters()); downloadUrl(other.getDownloadUrl()); continueOnError(other.getContinueOnError()); @@ -111,13 +121,23 @@ public Builder from(V1DetokenizePayload other) { *

                                  Detokenization details.

                                  */ @JsonSetter(value = "detokenizationParameters", nulls = Nulls.SKIP) - public Builder detokenizationParameters(Optional> detokenizationParameters) { - this.detokenizationParameters = detokenizationParameters; + public Builder detokenizationParameters(List detokenizationParameters) { + this.detokenizationParameters.clear(); + if (detokenizationParameters != null) { + this.detokenizationParameters.addAll(detokenizationParameters); + } return this; } - public Builder detokenizationParameters(List detokenizationParameters) { - this.detokenizationParameters = Optional.ofNullable(detokenizationParameters); + public Builder addDetokenizationParameters(DetokenizeRecordRequest detokenizationParameters) { + this.detokenizationParameters.add(detokenizationParameters); + return this; + } + + public Builder addAllDetokenizationParameters(List detokenizationParameters) { + if (detokenizationParameters != null) { + this.detokenizationParameters.addAll(detokenizationParameters); + } return this; } @@ -149,9 +169,18 @@ public Builder continueOnError(Boolean continueOnError) { return this; } - public V1DetokenizePayload build() { - return new V1DetokenizePayload( - detokenizationParameters, downloadUrl, continueOnError, additionalProperties); + public DetokenizePayload build() { + return new DetokenizePayload(detokenizationParameters, downloadUrl, continueOnError, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DetokenizeRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DetokenizeRequest.java new file mode 100644 index 00000000..3424acdc --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/DetokenizeRequest.java @@ -0,0 +1,238 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.TokenGroupRedactions; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetokenizeRequest.Builder.class) +public final class DetokenizeRequest { + private final String vaultId; + + private final List tokens; + + private final Optional> tokenGroupRedactions; + + private final Map additionalProperties; + + private DetokenizeRequest( + String vaultId, + List tokens, + Optional> tokenGroupRedactions, + Map additionalProperties) { + this.vaultId = vaultId; + this.tokens = tokens; + this.tokenGroupRedactions = tokenGroupRedactions; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Token to be detokenized + */ + @JsonProperty("tokens") + public List getTokens() { + return tokens; + } + + /** + * @return List of token groups to redact. + */ + @JsonProperty("tokenGroupRedactions") + public Optional> getTokenGroupRedactions() { + return tokenGroupRedactions; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetokenizeRequest && equalTo((DetokenizeRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetokenizeRequest other) { + return vaultId.equals(other.vaultId) + && tokens.equals(other.tokens) + && tokenGroupRedactions.equals(other.tokenGroupRedactions); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.tokens, this.tokenGroupRedactions); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault.

                                  + */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(DetokenizeRequest other); + } + + public interface _FinalStage { + DetokenizeRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Token to be detokenized

                                  + */ + _FinalStage tokens(List tokens); + + _FinalStage addTokens(String tokens); + + _FinalStage addAllTokens(List tokens); + + /** + *

                                  List of token groups to redact.

                                  + */ + _FinalStage tokenGroupRedactions(Optional> tokenGroupRedactions); + + _FinalStage tokenGroupRedactions(List tokenGroupRedactions); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private Optional> tokenGroupRedactions = Optional.empty(); + + private List tokens = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DetokenizeRequest other) { + vaultId(other.getVaultId()); + tokens(other.getTokens()); + tokenGroupRedactions(other.getTokenGroupRedactions()); + return this; + } + + /** + *

                                  ID of the vault.

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

                                  List of token groups to redact.

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

                                  List of token groups to redact.

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

                                  Token to be detokenized

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllTokens(List tokens) { + if (tokens != null) { + this.tokens.addAll(tokens); + } + return this; + } + + /** + *

                                  Token to be detokenized

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

                                  Token to be detokenized

                                  + */ + @java.lang.Override + @JsonSetter(value = "tokens", nulls = Nulls.SKIP) + public _FinalStage tokens(List tokens) { + this.tokens.clear(); + if (tokens != null) { + this.tokens.addAll(tokens); + } + return this; + } + + @java.lang.Override + public DetokenizeRequest build() { + return new DetokenizeRequest(vaultId, tokens, tokenGroupRedactions, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/GetTokensFromValuesRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/GetTokensFromValuesRequest.java new file mode 100644 index 00000000..ffa9160b --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/GetTokensFromValuesRequest.java @@ -0,0 +1,191 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.GetTokensFromValuesRequestObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetTokensFromValuesRequest.Builder.class) +public final class GetTokensFromValuesRequest { + private final String vaultId; + + private final List records; + + private final Map additionalProperties; + + private GetTokensFromValuesRequest( + String vaultId, List records, Map additionalProperties) { + this.vaultId = vaultId; + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Array of value/token-group pairs to look up. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetTokensFromValuesRequest && equalTo((GetTokensFromValuesRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetTokensFromValuesRequest other) { + return vaultId.equals(other.vaultId) && records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault.

                                  + */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(GetTokensFromValuesRequest other); + } + + public interface _FinalStage { + GetTokensFromValuesRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Array of value/token-group pairs to look up.

                                  + */ + _FinalStage records(List records); + + _FinalStage addRecords(GetTokensFromValuesRequestObject records); + + _FinalStage addAllRecords(List records); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(GetTokensFromValuesRequest other) { + vaultId(other.getVaultId()); + records(other.getRecords()); + return this; + } + + /** + *

                                  ID of the vault.

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

                                  Array of value/token-group pairs to look up.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + /** + *

                                  Array of value/token-group pairs to look up.

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

                                  Array of value/token-group pairs to look up.

                                  + */ + @java.lang.Override + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public _FinalStage records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + @java.lang.Override + public GetTokensFromValuesRequest build() { + return new GetTokensFromValuesRequest(vaultId, records, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/TokenizePayload.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/TokenizePayload.java new file mode 100644 index 00000000..13466de6 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/TokenizePayload.java @@ -0,0 +1,124 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.TokenizeRecordRequest; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenizePayload.Builder.class) +public final class TokenizePayload { + private final List tokenizationParameters; + + private final Map additionalProperties; + + private TokenizePayload( + List tokenizationParameters, Map additionalProperties) { + this.tokenizationParameters = tokenizationParameters; + this.additionalProperties = additionalProperties; + } + + /** + * @return Tokenization details. + */ + @JsonProperty("tokenizationParameters") + public List getTokenizationParameters() { + return tokenizationParameters; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenizePayload && equalTo((TokenizePayload) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenizePayload other) { + return tokenizationParameters.equals(other.tokenizationParameters); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tokenizationParameters); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List tokenizationParameters = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(TokenizePayload other) { + tokenizationParameters(other.getTokenizationParameters()); + return this; + } + + /** + *

                                  Tokenization details.

                                  + */ + @JsonSetter(value = "tokenizationParameters", nulls = Nulls.SKIP) + public Builder tokenizationParameters(List tokenizationParameters) { + this.tokenizationParameters.clear(); + if (tokenizationParameters != null) { + this.tokenizationParameters.addAll(tokenizationParameters); + } + return this; + } + + public Builder addTokenizationParameters(TokenizeRecordRequest tokenizationParameters) { + this.tokenizationParameters.add(tokenizationParameters); + return this; + } + + public Builder addAllTokenizationParameters(List tokenizationParameters) { + if (tokenizationParameters != null) { + this.tokenizationParameters.addAll(tokenizationParameters); + } + return this; + } + + public TokenizePayload build() { + return new TokenizePayload(tokenizationParameters, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/TokenizeRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/TokenizeRequest.java new file mode 100644 index 00000000..7aab1a72 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/TokenizeRequest.java @@ -0,0 +1,191 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.TokenizeRequestObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenizeRequest.Builder.class) +public final class TokenizeRequest { + private final String vaultId; + + private final List data; + + private final Map additionalProperties; + + private TokenizeRequest( + String vaultId, List data, Map additionalProperties) { + this.vaultId = vaultId; + this.data = data; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public String getVaultId() { + return vaultId; + } + + /** + * @return Data to tokenize. + */ + @JsonProperty("data") + public List getData() { + return data; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenizeRequest && equalTo((TokenizeRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenizeRequest other) { + return vaultId.equals(other.vaultId) && data.equals(other.data); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.data); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + *

                                  ID of the vault.

                                  + */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(TokenizeRequest other); + } + + public interface _FinalStage { + TokenizeRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Data to tokenize.

                                  + */ + _FinalStage data(List data); + + _FinalStage addData(TokenizeRequestObject data); + + _FinalStage addAllData(List data); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + private List data = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(TokenizeRequest other) { + vaultId(other.getVaultId()); + data(other.getData()); + return this; + } + + /** + *

                                  ID of the vault.

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

                                  Data to tokenize.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllData(List data) { + if (data != null) { + this.data.addAll(data); + } + return this; + } + + /** + *

                                  Data to tokenize.

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

                                  Data to tokenize.

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

                                  Tokenization details.

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

                                  ID for the audit event.

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

                                  ID for the request that caused the event.

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

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

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

                                  ID for the session in which the request was sent.

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

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

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

                                  IP Address of the client that made the request.

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

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

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

                                  ID of the JWT token.

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

                                  Embedded User Context.

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

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

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

                                  The http URI that is used.

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

                                  http method used.

                                  - */ - @JsonSetter(value = "method", nulls = Nulls.SKIP) - public Builder method(Optional method) { - this.method = method; - return this; - } - - public Builder method(String method) { - this.method = Optional.ofNullable(method); - return this; - } - - public AuditEventHttpInfo build() { - return new AuditEventHttpInfo(uri, method, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1BatchOperationResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchOperationResponse.java similarity index 61% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/V1BatchOperationResponse.java rename to skyvault/src/main/java/com/skyflow/generated/rest/types/BatchOperationResponse.java index 8f5fb775..4b33661a 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1BatchOperationResponse.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchOperationResponse.java @@ -3,22 +3,31 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1BatchOperationResponse.Builder.class) -public final class V1BatchOperationResponse { +@JsonDeserialize(builder = BatchOperationResponse.Builder.class) +public final class BatchOperationResponse { private final Optional vaultId; private final Optional>> responses; private final Map additionalProperties; - private V1BatchOperationResponse( + private BatchOperationResponse( Optional vaultId, Optional>> responses, Map additionalProperties) { @@ -36,17 +45,17 @@ public Optional getVaultId() { } /** - * @return Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs: <br/><ul><li>POST returns an Insert Records response.</li><li>PUT returns an Update Record response.</li><li>GET returns a Get Record response.</li><li>DELETE returns a Delete Record response.</li></ul> + * @return Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs:
                                  • POST returns an Insert Records response.
                                  • PUT returns an Update Record response.
                                  • GET returns a Get Record response.
                                  • DELETE returns a Delete Record response.
                                  */ @JsonProperty("responses") public Optional>> getResponses() { return responses; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof V1BatchOperationResponse && equalTo((V1BatchOperationResponse) other); + return other instanceof BatchOperationResponse && equalTo((BatchOperationResponse) other); } @JsonAnyGetter @@ -54,16 +63,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(V1BatchOperationResponse other) { + private boolean equalTo(BatchOperationResponse other) { return vaultId.equals(other.vaultId) && responses.equals(other.responses); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.vaultId, this.responses); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -83,7 +92,7 @@ public static final class Builder { private Builder() {} - public Builder from(V1BatchOperationResponse other) { + public Builder from(BatchOperationResponse other) { vaultId(other.getVaultId()); responses(other.getResponses()); return this; @@ -104,7 +113,7 @@ public Builder vaultId(String vaultId) { } /** - *

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

                                  + *

                                  Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs:

                                  • POST returns an Insert Records response.
                                  • PUT returns an Update Record response.
                                  • GET returns a Get Record response.
                                  • DELETE returns a Delete Record response.

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

                                  Name of the table to perform the operation on.

                                  + */ + MethodStage tableName(@NotNull String tableName); + + Builder from(BatchRecord other); + } + + public interface MethodStage { + /** + *

                                  Method of the operation.

                                  + */ + _FinalStage method(@NotNull BatchRecordMethod method); + } + + public interface _FinalStage { + BatchRecord build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

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

                                  + */ + _FinalStage fields(Map fields); + + _FinalStage putAllFields(Map fields); + + _FinalStage fields(String key, Object value); + + /** + *

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

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

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

                                  + */ + _FinalStage redaction(Optional redaction); + + _FinalStage redaction(BatchRecordRedaction redaction); + + /** + *

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

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

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

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

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

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

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

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

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

                                  + */ + _FinalStage tokens(Optional> tokens); + + _FinalStage tokens(Map tokens); + + /** + *

                                  If true, returns metadata for files.

                                  + */ + _FinalStage returnFileMetadata(Optional returnFileMetadata); + + _FinalStage returnFileMetadata(Boolean returnFileMetadata); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TableNameStage, MethodStage, _FinalStage { + private String tableName; + + private BatchRecordMethod method; + + private Optional returnFileMetadata = Optional.empty(); + + private Optional> tokens = Optional.empty(); + + private Optional upsert = Optional.empty(); + + private Optional downloadUrl = Optional.empty(); + + private Optional id = Optional.empty(); + + private Optional tokenization = Optional.empty(); + + private Optional redaction = Optional.empty(); + + private Optional batchId = Optional.empty(); + + private Map fields = new LinkedHashMap<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(BatchRecord other) { + fields(other.getFields()); + tableName(other.getTableName()); + method(other.getMethod()); + batchId(other.getBatchId()); + redaction(other.getRedaction()); + tokenization(other.getTokenization()); + id(other.getId()); + downloadUrl(other.getDownloadUrl()); + upsert(other.getUpsert()); + tokens(other.getTokens()); + returnFileMetadata(other.getReturnFileMetadata()); + return this; + } + + /** + *

                                  Name of the table to perform the operation on.

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

                                  Method of the operation.

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

                                  If true, returns metadata for files.

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

                                  If true, returns metadata for files.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage fields(String key, Object value) { + this.fields.put(key, value); + return this; + } + + /** + *

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

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage putAllFields(Map fields) { + if (fields != null) { + this.fields.putAll(fields); + } + return this; + } + + /** + *

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

                                  + */ + @java.lang.Override + @JsonSetter(value = "fields", nulls = Nulls.SKIP) + public _FinalStage fields(Map fields) { + this.fields.clear(); + if (fields != null) { + this.fields.putAll(fields); + } + return this; + } + + @java.lang.Override + public BatchRecord build() { + return new BatchRecord( + fields, + tableName, + method, + batchId, + redaction, + tokenization, + id, + downloadUrl, + upsert, + tokens, + returnFileMetadata, + additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java index a6f5e673..85fc6185 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java @@ -3,28 +3,101 @@ */ package com.skyflow.generated.rest.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum BatchRecordMethod { - NONE("NONE"), +public final class BatchRecordMethod { + public static final BatchRecordMethod GET = new BatchRecordMethod(Value.GET, "GET"); - POST("POST"), + public static final BatchRecordMethod PUT = new BatchRecordMethod(Value.PUT, "PUT"); - PUT("PUT"), + public static final BatchRecordMethod DELETE = new BatchRecordMethod(Value.DELETE, "DELETE"); - GET("GET"), + public static final BatchRecordMethod POST = new BatchRecordMethod(Value.POST, "POST"); - DELETE("DELETE"); + private final Value value; - private final String value; + private final String string; - BatchRecordMethod(String value) { + BatchRecordMethod(Value value, String string) { this.value = value; + this.string = string; } + public Value getEnumValue() { + return value; + } + + @java.lang.Override @JsonValue - @Override public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof BatchRecordMethod && this.string.equals(((BatchRecordMethod) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case GET: + return visitor.visitGet(); + case PUT: + return visitor.visitPut(); + case DELETE: + return visitor.visitDelete(); + case POST: + return visitor.visitPost(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static BatchRecordMethod valueOf(String value) { + switch (value) { + case "GET": + return GET; + case "PUT": + return PUT; + case "DELETE": + return DELETE; + case "POST": + return POST; + default: + return new BatchRecordMethod(Value.UNKNOWN, value); + } + } + + public enum Value { + POST, + + PUT, + + GET, + + DELETE, + + UNKNOWN + } + + public interface Visitor { + T visitPost(); + + T visitPut(); + + T visitGet(); + + T visitDelete(); + + T visitUnknown(String unknownType); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchRecordRedaction.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchRecordRedaction.java new file mode 100644 index 00000000..07361521 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/BatchRecordRedaction.java @@ -0,0 +1,103 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class BatchRecordRedaction { + public static final BatchRecordRedaction DEFAULT = new BatchRecordRedaction(Value.DEFAULT, "DEFAULT"); + + public static final BatchRecordRedaction PLAIN_TEXT = new BatchRecordRedaction(Value.PLAIN_TEXT, "PLAIN_TEXT"); + + public static final BatchRecordRedaction MASKED = new BatchRecordRedaction(Value.MASKED, "MASKED"); + + public static final BatchRecordRedaction REDACTED = new BatchRecordRedaction(Value.REDACTED, "REDACTED"); + + private final Value value; + + private final String string; + + BatchRecordRedaction(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof BatchRecordRedaction && this.string.equals(((BatchRecordRedaction) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case DEFAULT: + return visitor.visitDefault(); + case PLAIN_TEXT: + return visitor.visitPlainText(); + case MASKED: + return visitor.visitMasked(); + case REDACTED: + return visitor.visitRedacted(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static BatchRecordRedaction valueOf(String value) { + switch (value) { + case "DEFAULT": + return DEFAULT; + case "PLAIN_TEXT": + return PLAIN_TEXT; + case "MASKED": + return MASKED; + case "REDACTED": + return REDACTED; + default: + return new BatchRecordRedaction(Value.UNKNOWN, value); + } + } + + public enum Value { + DEFAULT, + + REDACTED, + + MASKED, + + PLAIN_TEXT, + + UNKNOWN + } + + public interface Visitor { + T visitDefault(); + + T visitRedacted(); + + T visitMasked(); + + T visitPlainText(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1BulkDeleteRecordResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/BulkDeleteRecordResponse.java similarity index 61% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/V1BulkDeleteRecordResponse.java rename to skyvault/src/main/java/com/skyflow/generated/rest/types/BulkDeleteRecordResponse.java index b7151598..b698f904 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1BulkDeleteRecordResponse.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/BulkDeleteRecordResponse.java @@ -3,20 +3,29 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1BulkDeleteRecordResponse.Builder.class) -public final class V1BulkDeleteRecordResponse { +@JsonDeserialize(builder = BulkDeleteRecordResponse.Builder.class) +public final class BulkDeleteRecordResponse { private final Optional> recordIdResponse; private final Map additionalProperties; - private V1BulkDeleteRecordResponse( + private BulkDeleteRecordResponse( Optional> recordIdResponse, Map additionalProperties) { this.recordIdResponse = recordIdResponse; this.additionalProperties = additionalProperties; @@ -30,10 +39,10 @@ public Optional> getRecordIdResponse() { return recordIdResponse; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof V1BulkDeleteRecordResponse && equalTo((V1BulkDeleteRecordResponse) other); + return other instanceof BulkDeleteRecordResponse && equalTo((BulkDeleteRecordResponse) other); } @JsonAnyGetter @@ -41,16 +50,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(V1BulkDeleteRecordResponse other) { + private boolean equalTo(BulkDeleteRecordResponse other) { return recordIdResponse.equals(other.recordIdResponse); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.recordIdResponse); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -68,7 +77,7 @@ public static final class Builder { private Builder() {} - public Builder from(V1BulkDeleteRecordResponse other) { + public Builder from(BulkDeleteRecordResponse other) { recordIdResponse(other.getRecordIdResponse()); return this; } @@ -87,8 +96,18 @@ public Builder recordIdResponse(List recordIdResponse) { return this; } - public V1BulkDeleteRecordResponse build() { - return new V1BulkDeleteRecordResponse(recordIdResponse, additionalProperties); + public BulkDeleteRecordResponse build() { + return new BulkDeleteRecordResponse(recordIdResponse, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/BulkGetRecordResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/BulkGetRecordResponse.java new file mode 100644 index 00000000..c753c19b --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/BulkGetRecordResponse.java @@ -0,0 +1,112 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = BulkGetRecordResponse.Builder.class) +public final class BulkGetRecordResponse { + private final Optional> records; + + private final Map additionalProperties; + + private BulkGetRecordResponse(Optional> records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return The specified records. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof BulkGetRecordResponse && equalTo((BulkGetRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(BulkGetRecordResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(BulkGetRecordResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

                                  The specified records.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + public BulkGetRecordResponse build() { + return new BulkGetRecordResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ColumnRedactions.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ColumnRedactions.java new file mode 100644 index 00000000..d445af16 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/ColumnRedactions.java @@ -0,0 +1,160 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ColumnRedactions.Builder.class) +public final class ColumnRedactions { + private final String columnName; + + private final String redaction; + + private final Map additionalProperties; + + private ColumnRedactions(String columnName, String redaction, Map additionalProperties) { + this.columnName = columnName; + this.redaction = redaction; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the column to redact. + */ + @JsonProperty("columnName") + public String getColumnName() { + return columnName; + } + + /** + * @return Name of the redaction type. + */ + @JsonProperty("redaction") + public String getRedaction() { + return redaction; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ColumnRedactions && equalTo((ColumnRedactions) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ColumnRedactions other) { + return columnName.equals(other.columnName) && redaction.equals(other.redaction); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.columnName, this.redaction); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ColumnNameStage builder() { + return new Builder(); + } + + public interface ColumnNameStage { + /** + *

                                  Name of the column to redact.

                                  + */ + RedactionStage columnName(@NotNull String columnName); + + Builder from(ColumnRedactions other); + } + + public interface RedactionStage { + /** + *

                                  Name of the redaction type.

                                  + */ + _FinalStage redaction(@NotNull String redaction); + } + + public interface _FinalStage { + ColumnRedactions build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ColumnNameStage, RedactionStage, _FinalStage { + private String columnName; + + private String redaction; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ColumnRedactions other) { + columnName(other.getColumnName()); + redaction(other.getRedaction()); + return this; + } + + /** + *

                                  Name of the column to redact.

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

                                  Name of the redaction type.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("redaction") + public _FinalStage redaction(@NotNull String redaction) { + this.redaction = Objects.requireNonNull(redaction, "redaction must not be null"); + return this; + } + + @java.lang.Override + public ColumnRedactions build() { + return new ColumnRedactions(columnName, redaction, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ContextAccessType.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ContextAccessType.java deleted file mode 100644 index 163e862e..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ContextAccessType.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum ContextAccessType { - ACCESS_NONE("ACCESS_NONE"), - - API("API"), - - SQL("SQL"); - - private final String value; - - ContextAccessType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ContextAuthMode.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ContextAuthMode.java deleted file mode 100644 index 204ad039..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ContextAuthMode.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum ContextAuthMode { - AUTH_NONE("AUTH_NONE"), - - OKTA_JWT("OKTA_JWT"), - - SERVICE_ACCOUNT_JWT("SERVICE_ACCOUNT_JWT"), - - PAT_JWT("PAT_JWT"); - - private final String value; - - ContextAuthMode(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutputProcessedFileExtension.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutputProcessedFileExtension.java deleted file mode 100644 index febaeca3..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutputProcessedFileExtension.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifiedFileOutputProcessedFileExtension { - MP_3("mp3"), - - WAV("wav"), - - PDF("pdf"), - - TXT("txt"), - - CSV("csv"), - - JSON("json"), - - JPG("jpg"), - - JPEG("jpeg"), - - TIF("tif"), - - TIFF("tiff"), - - PNG("png"), - - BMP("bmp"), - - XLS("xls"), - - XLSX("xlsx"), - - DOC("doc"), - - DOCX("docx"), - - PPT("ppt"), - - PPTX("pptx"), - - XML("xml"), - - DCM("dcm"); - - private final String value; - - DeidentifiedFileOutputProcessedFileExtension(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutputProcessedFileType.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutputProcessedFileType.java deleted file mode 100644 index e020b28f..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifiedFileOutputProcessedFileType.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DeidentifiedFileOutputProcessedFileType { - REDACTED_AUDIO("redacted_audio"), - - REDACTED_IMAGE("redacted_image"), - - REDACTED_TRANSCRIPTION("redacted_transcription"), - - REDACTED_FILE("redacted_file"), - - REDACTED_TEXT("redacted_text"), - - ENTITIES("entities"), - - REDACTED_TRANSCRIPTION_DIARIZE_JSON("redacted_transcription_diarize_json"); - - private final String value; - - DeidentifiedFileOutputProcessedFileType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifyStringResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifyStringResponse.java deleted file mode 100644 index 1389fa0f..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeidentifyStringResponse.java +++ /dev/null @@ -1,186 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DeidentifyStringResponse.Builder.class) -public final class DeidentifyStringResponse { - private final Optional processedText; - - private final Optional> entities; - - private final Optional wordCount; - - private final Optional characterCount; - - private final Map additionalProperties; - - private DeidentifyStringResponse( - Optional processedText, - Optional> entities, - Optional wordCount, - Optional characterCount, - Map additionalProperties) { - this.processedText = processedText; - this.entities = entities; - this.wordCount = wordCount; - this.characterCount = characterCount; - this.additionalProperties = additionalProperties; - } - - /** - * @return De-identified text. - */ - @JsonProperty("processed_text") - public Optional getProcessedText() { - return processedText; - } - - /** - * @return Detected entities. - */ - @JsonProperty("entities") - public Optional> getEntities() { - return entities; - } - - /** - * @return Number of words from the input text. - */ - @JsonProperty("word_count") - public Optional getWordCount() { - return wordCount; - } - - /** - * @return Number of characters from the input text. - */ - @JsonProperty("character_count") - public Optional getCharacterCount() { - return characterCount; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DeidentifyStringResponse && equalTo((DeidentifyStringResponse) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DeidentifyStringResponse other) { - return processedText.equals(other.processedText) - && entities.equals(other.entities) - && wordCount.equals(other.wordCount) - && characterCount.equals(other.characterCount); - } - - @Override - public int hashCode() { - return Objects.hash(this.processedText, this.entities, this.wordCount, this.characterCount); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional processedText = Optional.empty(); - - private Optional> entities = Optional.empty(); - - private Optional wordCount = Optional.empty(); - - private Optional characterCount = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(DeidentifyStringResponse other) { - processedText(other.getProcessedText()); - entities(other.getEntities()); - wordCount(other.getWordCount()); - characterCount(other.getCharacterCount()); - return this; - } - - /** - *

                                  De-identified text.

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

                                  Detected entities.

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

                                  Number of words from the input text.

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

                                  Number of characters from the input text.

                                  - */ - @JsonSetter(value = "character_count", nulls = Nulls.SKIP) - public Builder characterCount(Optional characterCount) { - this.characterCount = characterCount; - return this; - } - - public Builder characterCount(Integer characterCount) { - this.characterCount = Optional.ofNullable(characterCount); - return this; - } - - public DeidentifyStringResponse build() { - return new DeidentifyStringResponse( - processedText, entities, wordCount, characterCount, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1DeleteRecordResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteRecordResponse.java similarity index 70% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/V1DeleteRecordResponse.java rename to skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteRecordResponse.java index 5351d897..7b7c731b 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1DeleteRecordResponse.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteRecordResponse.java @@ -3,25 +3,30 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; - import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1DeleteRecordResponse.Builder.class) -public final class V1DeleteRecordResponse { +@JsonDeserialize(builder = DeleteRecordResponse.Builder.class) +public final class DeleteRecordResponse { private final Optional skyflowId; private final Optional deleted; private final Map additionalProperties; - private V1DeleteRecordResponse( + private DeleteRecordResponse( Optional skyflowId, Optional deleted, Map additionalProperties) { this.skyflowId = skyflowId; this.deleted = deleted; @@ -44,10 +49,10 @@ public Optional getDeleted() { return deleted; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof V1DeleteRecordResponse && equalTo((V1DeleteRecordResponse) other); + return other instanceof DeleteRecordResponse && equalTo((DeleteRecordResponse) other); } @JsonAnyGetter @@ -55,16 +60,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(V1DeleteRecordResponse other) { + private boolean equalTo(DeleteRecordResponse other) { return skyflowId.equals(other.skyflowId) && deleted.equals(other.deleted); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.skyflowId, this.deleted); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -84,7 +89,7 @@ public static final class Builder { private Builder() {} - public Builder from(V1DeleteRecordResponse other) { + public Builder from(DeleteRecordResponse other) { skyflowId(other.getSkyflowId()); deleted(other.getDeleted()); return this; @@ -118,8 +123,18 @@ public Builder deleted(Boolean deleted) { return this; } - public V1DeleteRecordResponse build() { - return new V1DeleteRecordResponse(skyflowId, deleted, additionalProperties); + public DeleteRecordResponse build() { + return new DeleteRecordResponse(skyflowId, deleted, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteResponse.java new file mode 100644 index 00000000..8b2845c5 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteResponse.java @@ -0,0 +1,122 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeleteResponse.Builder.class) +public final class DeleteResponse { + private final List records; + + private final Map additionalProperties; + + private DeleteResponse(List records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return List of deleted records with skyflow ID and any partial errors. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeleteResponse && equalTo((DeleteResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeleteResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DeleteResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

                                  List of deleted records with skyflow ID and any partial errors.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(DeleteResponseObject records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public DeleteResponse build() { + return new DeleteResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteResponseObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteResponseObject.java new file mode 100644 index 00000000..2b743afa --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteResponseObject.java @@ -0,0 +1,204 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeleteResponseObject.Builder.class) +public final class DeleteResponseObject { + private final String skyflowId; + + private final Optional error; + + private final int httpCode; + + private final Map additionalProperties; + + private DeleteResponseObject( + String skyflowId, Optional error, int httpCode, Map additionalProperties) { + this.skyflowId = skyflowId; + this.error = error; + this.httpCode = httpCode; + this.additionalProperties = additionalProperties; + } + + /** + * @return Skyflow ID of the deleted record. + */ + @JsonProperty("skyflowID") + public String getSkyflowId() { + return skyflowId; + } + + /** + * @return Error message, if any. + */ + @JsonProperty("error") + public Optional getError() { + return error; + } + + /** + * @return HTTP status code of the response. + */ + @JsonProperty("httpCode") + public int getHttpCode() { + return httpCode; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeleteResponseObject && equalTo((DeleteResponseObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeleteResponseObject other) { + return skyflowId.equals(other.skyflowId) && error.equals(other.error) && httpCode == other.httpCode; + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.error, this.httpCode); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static SkyflowIdStage builder() { + return new Builder(); + } + + public interface SkyflowIdStage { + /** + *

                                  Skyflow ID of the deleted record.

                                  + */ + HttpCodeStage skyflowId(@NotNull String skyflowId); + + Builder from(DeleteResponseObject other); + } + + public interface HttpCodeStage { + /** + *

                                  HTTP status code of the response.

                                  + */ + _FinalStage httpCode(int httpCode); + } + + public interface _FinalStage { + DeleteResponseObject build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Error message, if any.

                                  + */ + _FinalStage error(Optional error); + + _FinalStage error(String error); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements SkyflowIdStage, HttpCodeStage, _FinalStage { + private String skyflowId; + + private int httpCode; + + private Optional error = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeleteResponseObject other) { + skyflowId(other.getSkyflowId()); + error(other.getError()); + httpCode(other.getHttpCode()); + return this; + } + + /** + *

                                  Skyflow ID of the deleted record.

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

                                  HTTP status code of the response.

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

                                  Error message, if any.

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

                                  Error message, if any.

                                  + */ + @java.lang.Override + @JsonSetter(value = "error", nulls = Nulls.SKIP) + public _FinalStage error(Optional error) { + this.error = error; + return this; + } + + @java.lang.Override + public DeleteResponseObject build() { + return new DeleteResponseObject(skyflowId, error, httpCode, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteTokenResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteTokenResponse.java new file mode 100644 index 00000000..d651c5d9 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteTokenResponse.java @@ -0,0 +1,122 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeleteTokenResponse.Builder.class) +public final class DeleteTokenResponse { + private final List tokens; + + private final Map additionalProperties; + + private DeleteTokenResponse(List tokens, Map additionalProperties) { + this.tokens = tokens; + this.additionalProperties = additionalProperties; + } + + /** + * @return Tokens data for Delete + */ + @JsonProperty("tokens") + public List getTokens() { + return tokens; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeleteTokenResponse && equalTo((DeleteTokenResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeleteTokenResponse other) { + return tokens.equals(other.tokens); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tokens); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List tokens = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DeleteTokenResponse other) { + tokens(other.getTokens()); + return this; + } + + /** + *

                                  Tokens data for Delete

                                  + */ + @JsonSetter(value = "tokens", nulls = Nulls.SKIP) + public Builder tokens(List tokens) { + this.tokens.clear(); + if (tokens != null) { + this.tokens.addAll(tokens); + } + return this; + } + + public Builder addTokens(DeleteTokenResponseObject tokens) { + this.tokens.add(tokens); + return this; + } + + public Builder addAllTokens(List tokens) { + if (tokens != null) { + this.tokens.addAll(tokens); + } + return this; + } + + public DeleteTokenResponse build() { + return new DeleteTokenResponse(tokens, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteTokenResponseObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteTokenResponseObject.java new file mode 100644 index 00000000..cd3c1698 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DeleteTokenResponseObject.java @@ -0,0 +1,171 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeleteTokenResponseObject.Builder.class) +public final class DeleteTokenResponseObject { + private final Optional value; + + private final Optional error; + + private final Optional httpCode; + + private final Map additionalProperties; + + private DeleteTokenResponseObject( + Optional value, + Optional error, + Optional httpCode, + Map additionalProperties) { + this.value = value; + this.error = error; + this.httpCode = httpCode; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token to be deleted. + */ + @JsonProperty("value") + public Optional getValue() { + return value; + } + + /** + * @return Error message, if any. + */ + @JsonProperty("error") + public Optional getError() { + return error; + } + + /** + * @return HTTP status code of the response. + */ + @JsonProperty("httpCode") + public Optional getHttpCode() { + return httpCode; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeleteTokenResponseObject && equalTo((DeleteTokenResponseObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeleteTokenResponseObject other) { + return value.equals(other.value) && error.equals(other.error) && httpCode.equals(other.httpCode); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value, this.error, this.httpCode); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional value = Optional.empty(); + + private Optional error = Optional.empty(); + + private Optional httpCode = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DeleteTokenResponseObject other) { + value(other.getValue()); + error(other.getError()); + httpCode(other.getHttpCode()); + return this; + } + + /** + *

                                  Token to be deleted.

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

                                  Error message, if any.

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

                                  HTTP status code of the response.

                                  + */ + @JsonSetter(value = "httpCode", nulls = Nulls.SKIP) + public Builder httpCode(Optional httpCode) { + this.httpCode = httpCode; + return this; + } + + public Builder httpCode(Integer httpCode) { + this.httpCode = Optional.ofNullable(httpCode); + return this; + } + + public DeleteTokenResponseObject build() { + return new DeleteTokenResponseObject(value, error, httpCode, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectGuardrailsResponseValidation.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectGuardrailsResponseValidation.java deleted file mode 100644 index e8bf032e..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectGuardrailsResponseValidation.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DetectGuardrailsResponseValidation { - FAILED("failed"), - - PASSED("passed"); - - private final String value; - - DetectGuardrailsResponseValidation(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponse.java deleted file mode 100644 index b73f7845..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponse.java +++ /dev/null @@ -1,348 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DetectRunsResponse.Builder.class) -public final class DetectRunsResponse { - private final Optional status; - - private final Optional outputType; - - private final Optional> output; - - private final Optional message; - - private final Optional size; - - private final Optional wordCharacterCount; - - private final Optional duration; - - private final Optional pages; - - private final Optional slides; - - private final Map additionalProperties; - - private DetectRunsResponse( - Optional status, - Optional outputType, - Optional> output, - Optional message, - Optional size, - Optional wordCharacterCount, - Optional duration, - Optional pages, - Optional slides, - Map additionalProperties) { - this.status = status; - this.outputType = outputType; - this.output = output; - this.message = message; - this.size = size; - this.wordCharacterCount = wordCharacterCount; - this.duration = duration; - this.pages = pages; - this.slides = slides; - this.additionalProperties = additionalProperties; - } - - /** - * @return Status of the operation. - */ - @JsonProperty("status") - public Optional getStatus() { - return status; - } - - /** - * @return Format of the output file. - */ - @JsonProperty("outputType") - public Optional getOutputType() { - return outputType; - } - - /** - * @return Details of output files. Files are specified as Base64-encoded data. - */ - @JsonProperty("output") - public Optional> getOutput() { - return output; - } - - /** - * @return Status details about the Detect run. - */ - @JsonProperty("message") - public Optional getMessage() { - return message; - } - - /** - * @return Size of the processed file in kilobytes (KB). - */ - @JsonProperty("size") - public Optional getSize() { - return size; - } - - @JsonProperty("wordCharacterCount") - public Optional getWordCharacterCount() { - return wordCharacterCount; - } - - /** - * @return Duration of the processed audio in seconds. - */ - @JsonProperty("duration") - public Optional getDuration() { - return duration; - } - - /** - * @return Number of pages in the processed PDF. - */ - @JsonProperty("pages") - public Optional getPages() { - return pages; - } - - /** - * @return Number of slides in the processed presentation. - */ - @JsonProperty("slides") - public Optional getSlides() { - return slides; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DetectRunsResponse && equalTo((DetectRunsResponse) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DetectRunsResponse other) { - return status.equals(other.status) - && outputType.equals(other.outputType) - && output.equals(other.output) - && message.equals(other.message) - && size.equals(other.size) - && wordCharacterCount.equals(other.wordCharacterCount) - && duration.equals(other.duration) - && pages.equals(other.pages) - && slides.equals(other.slides); - } - - @Override - public int hashCode() { - return Objects.hash( - this.status, - this.outputType, - this.output, - this.message, - this.size, - this.wordCharacterCount, - this.duration, - this.pages, - this.slides); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional status = Optional.empty(); - - private Optional outputType = Optional.empty(); - - private Optional> output = Optional.empty(); - - private Optional message = Optional.empty(); - - private Optional size = Optional.empty(); - - private Optional wordCharacterCount = Optional.empty(); - - private Optional duration = Optional.empty(); - - private Optional pages = Optional.empty(); - - private Optional slides = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(DetectRunsResponse other) { - status(other.getStatus()); - outputType(other.getOutputType()); - output(other.getOutput()); - message(other.getMessage()); - size(other.getSize()); - wordCharacterCount(other.getWordCharacterCount()); - duration(other.getDuration()); - pages(other.getPages()); - slides(other.getSlides()); - return this; - } - - /** - *

                                  Status of the operation.

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

                                  Format of the output file.

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

                                  Details of output files. Files are specified as Base64-encoded data.

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

                                  Status details about the Detect run.

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

                                  Size of the processed file in kilobytes (KB).

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

                                  Duration of the processed audio in seconds.

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

                                  Number of pages in the processed PDF.

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

                                  Number of slides in the processed presentation.

                                  - */ - @JsonSetter(value = "slides", nulls = Nulls.SKIP) - public Builder slides(Optional slides) { - this.slides = slides; - return this; - } - - public Builder slides(Integer slides) { - this.slides = Optional.ofNullable(slides); - return this; - } - - public DetectRunsResponse build() { - return new DetectRunsResponse( - status, - outputType, - output, - message, - size, - wordCharacterCount, - duration, - pages, - slides, - additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponseOutputType.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponseOutputType.java deleted file mode 100644 index 171dd153..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponseOutputType.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DetectRunsResponseOutputType { - UNKNOWN("UNKNOWN"), - - BASE_64("BASE64"); - - private final String value; - - DetectRunsResponseOutputType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponseStatus.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponseStatus.java deleted file mode 100644 index e5fa80d4..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetectRunsResponseStatus.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DetectRunsResponseStatus { - UNKNOWN("UNKNOWN"), - - FAILED("FAILED"), - - SUCCESS("SUCCESS"), - - IN_PROGRESS("IN_PROGRESS"); - - private final String value; - - DetectRunsResponseStatus(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordRequest.java new file mode 100644 index 00000000..2328e6fc --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordRequest.java @@ -0,0 +1,174 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetokenizeRecordRequest.Builder.class) +public final class DetokenizeRecordRequest { + private final String token; + + private final Optional redaction; + + private final Map additionalProperties; + + private DetokenizeRecordRequest( + String token, + Optional redaction, + Map additionalProperties) { + this.token = token; + this.redaction = redaction; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token that identifies the record to detokenize. + */ + @JsonProperty("token") + public String getToken() { + return token; + } + + /** + * @return Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. + */ + @JsonProperty("redaction") + public Optional getRedaction() { + return redaction; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetokenizeRecordRequest && equalTo((DetokenizeRecordRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetokenizeRecordRequest other) { + return token.equals(other.token) && redaction.equals(other.redaction); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token, this.redaction); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TokenStage builder() { + return new Builder(); + } + + public interface TokenStage { + /** + *

                                  Token that identifies the record to detokenize.

                                  + */ + _FinalStage token(@NotNull String token); + + Builder from(DetokenizeRecordRequest other); + } + + public interface _FinalStage { + DetokenizeRecordRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

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

                                  + */ + _FinalStage redaction(Optional redaction); + + _FinalStage redaction(DetokenizeRecordRequestRedaction redaction); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TokenStage, _FinalStage { + private String token; + + private Optional redaction = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DetokenizeRecordRequest other) { + token(other.getToken()); + redaction(other.getRedaction()); + return this; + } + + /** + *

                                  Token that identifies the record to detokenize.

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

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

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

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

                                  + */ + @java.lang.Override + @JsonSetter(value = "redaction", nulls = Nulls.SKIP) + public _FinalStage redaction(Optional redaction) { + this.redaction = redaction; + return this; + } + + @java.lang.Override + public DetokenizeRecordRequest build() { + return new DetokenizeRecordRequest(token, redaction, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordRequestRedaction.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordRequestRedaction.java new file mode 100644 index 00000000..0578f30a --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordRequestRedaction.java @@ -0,0 +1,108 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class DetokenizeRecordRequestRedaction { + public static final DetokenizeRecordRequestRedaction DEFAULT = + new DetokenizeRecordRequestRedaction(Value.DEFAULT, "DEFAULT"); + + public static final DetokenizeRecordRequestRedaction PLAIN_TEXT = + new DetokenizeRecordRequestRedaction(Value.PLAIN_TEXT, "PLAIN_TEXT"); + + public static final DetokenizeRecordRequestRedaction MASKED = + new DetokenizeRecordRequestRedaction(Value.MASKED, "MASKED"); + + public static final DetokenizeRecordRequestRedaction REDACTED = + new DetokenizeRecordRequestRedaction(Value.REDACTED, "REDACTED"); + + private final Value value; + + private final String string; + + DetokenizeRecordRequestRedaction(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetokenizeRecordRequestRedaction + && this.string.equals(((DetokenizeRecordRequestRedaction) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case DEFAULT: + return visitor.visitDefault(); + case PLAIN_TEXT: + return visitor.visitPlainText(); + case MASKED: + return visitor.visitMasked(); + case REDACTED: + return visitor.visitRedacted(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetokenizeRecordRequestRedaction valueOf(String value) { + switch (value) { + case "DEFAULT": + return DEFAULT; + case "PLAIN_TEXT": + return PLAIN_TEXT; + case "MASKED": + return MASKED; + case "REDACTED": + return REDACTED; + default: + return new DetokenizeRecordRequestRedaction(Value.UNKNOWN, value); + } + } + + public enum Value { + DEFAULT, + + REDACTED, + + MASKED, + + PLAIN_TEXT, + + UNKNOWN + } + + public interface Visitor { + T visitDefault(); + + T visitRedacted(); + + T visitMasked(); + + T visitPlainText(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponse.java new file mode 100644 index 00000000..2aeecd0e --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponse.java @@ -0,0 +1,203 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetokenizeRecordResponse.Builder.class) +public final class DetokenizeRecordResponse { + private final Optional token; + + private final Optional valueType; + + private final Optional value; + + private final Optional error; + + private final Map additionalProperties; + + private DetokenizeRecordResponse( + Optional token, + Optional valueType, + Optional value, + Optional error, + Map additionalProperties) { + this.token = token; + this.valueType = valueType; + this.value = value; + this.error = error; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token of the record. + */ + @JsonProperty("token") + public Optional getToken() { + return token; + } + + /** + * @return Data type of the value. + */ + @JsonProperty("valueType") + public Optional getValueType() { + return valueType; + } + + /** + * @return Data corresponding to the token. + */ + @JsonProperty("value") + public Optional getValue() { + return value; + } + + /** + * @return Error if token isn't found. + */ + @JsonProperty("error") + public Optional getError() { + return error; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetokenizeRecordResponse && equalTo((DetokenizeRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetokenizeRecordResponse other) { + return token.equals(other.token) + && valueType.equals(other.valueType) + && value.equals(other.value) + && error.equals(other.error); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token, this.valueType, this.value, this.error); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional token = Optional.empty(); + + private Optional valueType = Optional.empty(); + + private Optional value = Optional.empty(); + + private Optional error = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetokenizeRecordResponse other) { + token(other.getToken()); + valueType(other.getValueType()); + value(other.getValue()); + error(other.getError()); + return this; + } + + /** + *

                                  Token of the record.

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

                                  Data type of the value.

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

                                  Data corresponding to the token.

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

                                  Error if token isn't found.

                                  + */ + @JsonSetter(value = "error", nulls = Nulls.SKIP) + public Builder error(Optional error) { + this.error = error; + return this; + } + + public Builder error(String error) { + this.error = Optional.ofNullable(error); + return this; + } + + public DetokenizeRecordResponse build() { + return new DetokenizeRecordResponse(token, valueType, value, error, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponseValueType.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponseValueType.java index e9f4be2a..990dac21 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponseValueType.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponseValueType.java @@ -3,36 +3,161 @@ */ package com.skyflow.generated.rest.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum DetokenizeRecordResponseValueType { - NONE("NONE"), +public final class DetokenizeRecordResponseValueType { + public static final DetokenizeRecordResponseValueType FLOAT = + new DetokenizeRecordResponseValueType(Value.FLOAT, "FLOAT"); - STRING("STRING"), + public static final DetokenizeRecordResponseValueType ARRAY = + new DetokenizeRecordResponseValueType(Value.ARRAY, "ARRAY"); - INTEGER("INTEGER"), + public static final DetokenizeRecordResponseValueType TIME = + new DetokenizeRecordResponseValueType(Value.TIME, "TIME"); - FLOAT("FLOAT"), + public static final DetokenizeRecordResponseValueType DATE = + new DetokenizeRecordResponseValueType(Value.DATE, "DATE"); - BOOL("BOOL"), + public static final DetokenizeRecordResponseValueType INTEGER = + new DetokenizeRecordResponseValueType(Value.INTEGER, "INTEGER"); - DATETIME("DATETIME"), + public static final DetokenizeRecordResponseValueType JSON = + new DetokenizeRecordResponseValueType(Value.JSON, "JSON"); - JSON("JSON"), + public static final DetokenizeRecordResponseValueType BOOL = + new DetokenizeRecordResponseValueType(Value.BOOL, "BOOL"); - ARRAY("ARRAY"), + public static final DetokenizeRecordResponseValueType DATETIME = + new DetokenizeRecordResponseValueType(Value.DATETIME, "DATETIME"); - DATE("DATE"); + public static final DetokenizeRecordResponseValueType STRING = + new DetokenizeRecordResponseValueType(Value.STRING, "STRING"); - private final String value; + private final Value value; - DetokenizeRecordResponseValueType(String value) { + private final String string; + + DetokenizeRecordResponseValueType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } + @java.lang.Override @JsonValue - @Override public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DetokenizeRecordResponseValueType + && this.string.equals(((DetokenizeRecordResponseValueType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case FLOAT: + return visitor.visitFloat(); + case ARRAY: + return visitor.visitArray(); + case TIME: + return visitor.visitTime(); + case DATE: + return visitor.visitDate(); + case INTEGER: + return visitor.visitInteger(); + case JSON: + return visitor.visitJson(); + case BOOL: + return visitor.visitBool(); + case DATETIME: + return visitor.visitDatetime(); + case STRING: + return visitor.visitString(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DetokenizeRecordResponseValueType valueOf(String value) { + switch (value) { + case "FLOAT": + return FLOAT; + case "ARRAY": + return ARRAY; + case "TIME": + return TIME; + case "DATE": + return DATE; + case "INTEGER": + return INTEGER; + case "JSON": + return JSON; + case "BOOL": + return BOOL; + case "DATETIME": + return DATETIME; + case "STRING": + return STRING; + default: + return new DetokenizeRecordResponseValueType(Value.UNKNOWN, value); + } + } + + public enum Value { + STRING, + + INTEGER, + + FLOAT, + + BOOL, + + DATETIME, + + JSON, + + ARRAY, + + DATE, + + TIME, + + UNKNOWN + } + + public interface Visitor { + T visitString(); + + T visitInteger(); + + T visitFloat(); + + T visitBool(); + + T visitDatetime(); + + T visitJson(); + + T visitArray(); + + T visitDate(); + + T visitTime(); + + T visitUnknown(String unknownType); } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeResponse.java new file mode 100644 index 00000000..c16f5cb3 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeResponse.java @@ -0,0 +1,113 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetokenizeResponse.Builder.class) +public final class DetokenizeResponse { + private final Optional> records; + + private final Map additionalProperties; + + private DetokenizeResponse( + Optional> records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return Records corresponding to the specified tokens. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetokenizeResponse && equalTo((DetokenizeResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetokenizeResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetokenizeResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

                                  Records corresponding to the specified tokens.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + public DetokenizeResponse build() { + return new DetokenizeResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeResponseObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeResponseObject.java new file mode 100644 index 00000000..1848b425 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/DetokenizeResponseObject.java @@ -0,0 +1,335 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetokenizeResponseObject.Builder.class) +public final class DetokenizeResponseObject { + private final String token; + + private final Optional value; + + private final Optional tokenGroupName; + + private final Optional error; + + private final Optional httpCode; + + private final Optional> metadata; + + private final Map additionalProperties; + + private DetokenizeResponseObject( + String token, + Optional value, + Optional tokenGroupName, + Optional error, + Optional httpCode, + Optional> metadata, + Map additionalProperties) { + this.token = token; + this.value = value; + this.tokenGroupName = tokenGroupName; + this.error = error; + this.httpCode = httpCode; + this.metadata = metadata; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token that was detokenized. + */ + @JsonProperty("token") + public String getToken() { + return token; + } + + @JsonProperty("value") + public Optional getValue() { + return value; + } + + /** + * @return Name of the token group. + */ + @JsonProperty("tokenGroupName") + public Optional getTokenGroupName() { + return tokenGroupName; + } + + /** + * @return Error message, if any. + */ + @JsonProperty("error") + public Optional getError() { + return error; + } + + /** + * @return HTTP status code of the response. + */ + @JsonProperty("httpCode") + public Optional getHttpCode() { + return httpCode; + } + + /** + * @return Additional metadata associated with the token, such as tableName or skyflowID. + */ + @JsonProperty("metadata") + public Optional> getMetadata() { + return metadata; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetokenizeResponseObject && equalTo((DetokenizeResponseObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetokenizeResponseObject other) { + return token.equals(other.token) + && value.equals(other.value) + && tokenGroupName.equals(other.tokenGroupName) + && error.equals(other.error) + && httpCode.equals(other.httpCode) + && metadata.equals(other.metadata); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token, this.value, this.tokenGroupName, this.error, this.httpCode, this.metadata); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TokenStage builder() { + return new Builder(); + } + + public interface TokenStage { + /** + *

                                  Token that was detokenized.

                                  + */ + _FinalStage token(@NotNull String token); + + Builder from(DetokenizeResponseObject other); + } + + public interface _FinalStage { + DetokenizeResponseObject build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + _FinalStage value(Optional value); + + _FinalStage value(GoogleProtobufValue value); + + /** + *

                                  Name of the token group.

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

                                  Error message, if any.

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

                                  HTTP status code of the response.

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

                                  Additional metadata associated with the token, such as tableName or skyflowID.

                                  + */ + _FinalStage metadata(Optional> metadata); + + _FinalStage metadata(Map metadata); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TokenStage, _FinalStage { + private String token; + + private Optional> metadata = Optional.empty(); + + private Optional httpCode = Optional.empty(); + + private Optional error = Optional.empty(); + + private Optional tokenGroupName = Optional.empty(); + + private Optional value = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DetokenizeResponseObject other) { + token(other.getToken()); + value(other.getValue()); + tokenGroupName(other.getTokenGroupName()); + error(other.getError()); + httpCode(other.getHttpCode()); + metadata(other.getMetadata()); + return this; + } + + /** + *

                                  Token that was detokenized.

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

                                  Additional metadata associated with the token, such as tableName or skyflowID.

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

                                  Additional metadata associated with the token, such as tableName or skyflowID.

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

                                  HTTP status code of the response.

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

                                  HTTP status code of the response.

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

                                  Error message, if any.

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

                                  Error message, if any.

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

                                  Name of the token group.

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

                                  Name of the token group.

                                  + */ + @java.lang.Override + @JsonSetter(value = "tokenGroupName", nulls = Nulls.SKIP) + public _FinalStage tokenGroupName(Optional tokenGroupName) { + this.tokenGroupName = tokenGroupName; + return this; + } + + @java.lang.Override + public _FinalStage value(GoogleProtobufValue value) { + this.value = Optional.ofNullable(value); + return this; + } + + @java.lang.Override + @JsonSetter(value = "value", nulls = Nulls.SKIP) + public _FinalStage value(Optional value) { + this.value = value; + return this; + } + + @java.lang.Override + public DetokenizeResponseObject build() { + return new DetokenizeResponseObject( + token, value, tokenGroupName, error, httpCode, metadata, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ErrorResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ErrorResponse.java index 4113b998..3becce63 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ErrorResponse.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/ErrorResponse.java @@ -3,14 +3,18 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; -import org.jetbrains.annotations.NotNull; - import java.util.HashMap; import java.util.Map; import java.util.Objects; +import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = ErrorResponse.Builder.class) @@ -29,7 +33,7 @@ public ErrorResponseError getError() { return error; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; return other instanceof ErrorResponse && equalTo((ErrorResponse) other); @@ -44,12 +48,12 @@ private boolean equalTo(ErrorResponse other) { return error.equals(other.error); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.error); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -66,6 +70,10 @@ public interface ErrorStage { public interface _FinalStage { ErrorResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties(ignoreUnknown = true) @@ -77,22 +85,34 @@ public static final class Builder implements ErrorStage, _FinalStage { private Builder() {} - @Override + @java.lang.Override public Builder from(ErrorResponse other) { error(other.getError()); return this; } - @Override + @java.lang.Override @JsonSetter("error") public _FinalStage error(@NotNull ErrorResponseError error) { this.error = Objects.requireNonNull(error, "error must not be null"); return this; } - @Override + @java.lang.Override public ErrorResponse build() { return new ErrorResponse(error, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ErrorResponseError.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ErrorResponseError.java index 4774fa57..a10d36cc 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ErrorResponseError.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/ErrorResponseError.java @@ -3,13 +3,22 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.jetbrains.annotations.NotNull; -import java.util.*; - @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = ErrorResponseError.Builder.class) public final class ErrorResponseError { @@ -68,7 +77,7 @@ public Optional>> getDetails() { return details; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; return other instanceof ErrorResponseError && equalTo((ErrorResponseError) other); @@ -87,12 +96,12 @@ private boolean equalTo(ErrorResponseError other) { && details.equals(other.details); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.grpcCode, this.httpCode, this.httpStatus, this.message, this.details); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -103,7 +112,7 @@ public static GrpcCodeStage builder() { public interface GrpcCodeStage { /** - * gRPC status codes. See https://grpc.io/docs/guides/status-codes. + *

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

                                  */ HttpCodeStage grpcCode(int grpcCode); @@ -125,6 +134,10 @@ public interface MessageStage { public interface _FinalStage { ErrorResponseError build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage details(Optional>> details); _FinalStage details(List> details); @@ -148,7 +161,7 @@ public static final class Builder private Builder() {} - @Override + @java.lang.Override public Builder from(ErrorResponseError other) { grpcCode(other.getGrpcCode()); httpCode(other.getHttpCode()); @@ -159,53 +172,65 @@ public Builder from(ErrorResponseError other) { } /** - * gRPC status codes. See https://grpc.io/docs/guides/status-codes.

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

                                  + *

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

                                  * @return Reference to {@code this} so that method calls can be chained together. */ - @Override + @java.lang.Override @JsonSetter("grpc_code") public HttpCodeStage grpcCode(int grpcCode) { this.grpcCode = grpcCode; return this; } - @Override + @java.lang.Override @JsonSetter("http_code") public HttpStatusStage httpCode(int httpCode) { this.httpCode = httpCode; return this; } - @Override + @java.lang.Override @JsonSetter("http_status") public MessageStage httpStatus(@NotNull String httpStatus) { this.httpStatus = Objects.requireNonNull(httpStatus, "httpStatus must not be null"); return this; } - @Override + @java.lang.Override @JsonSetter("message") public _FinalStage message(@NotNull String message) { this.message = Objects.requireNonNull(message, "message must not be null"); return this; } - @Override + @java.lang.Override public _FinalStage details(List> details) { this.details = Optional.ofNullable(details); return this; } - @Override + @java.lang.Override @JsonSetter(value = "details", nulls = Nulls.SKIP) public _FinalStage details(Optional>> details) { this.details = details; return this; } - @Override + @java.lang.Override public ErrorResponseError build() { return new ErrorResponseError(grpcCode, httpCode, httpStatus, message, details, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ExecuteQueryRecordResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ExecuteQueryRecordResponse.java new file mode 100644 index 00000000..5c3433f4 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/ExecuteQueryRecordResponse.java @@ -0,0 +1,111 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ExecuteQueryRecordResponse.Builder.class) +public final class ExecuteQueryRecordResponse { + private final Optional> data; + + private final Map additionalProperties; + + private ExecuteQueryRecordResponse(Optional> data, Map additionalProperties) { + this.data = data; + this.additionalProperties = additionalProperties; + } + + /** + * @return Fields and values for the record. + */ + @JsonProperty("data") + public Optional> getData() { + return data; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ExecuteQueryRecordResponse && equalTo((ExecuteQueryRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ExecuteQueryRecordResponse other) { + return data.equals(other.data); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.data); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> data = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ExecuteQueryRecordResponse other) { + data(other.getData()); + return this; + } + + /** + *

                                  Fields and values for the record.

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

                                  Records corresponding to the specified query.

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

                                  Columns returned for the query.

                                  + */ + @JsonSetter(value = "columns", nulls = Nulls.SKIP) + public Builder columns(Optional> columns) { + this.columns = columns; + return this; + } + + public Builder columns(List columns) { + this.columns = Optional.ofNullable(columns); + return this; + } + + public ExecuteQueryResponseMetadata build() { + return new ExecuteQueryResponseMetadata(columns, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1FieldRecords.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FieldRecords.java similarity index 73% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/V1FieldRecords.java rename to skyvault/src/main/java/com/skyflow/generated/rest/types/FieldRecords.java index b64b8792..3fa42675 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1FieldRecords.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FieldRecords.java @@ -3,25 +3,30 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; - import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1FieldRecords.Builder.class) -public final class V1FieldRecords { +@JsonDeserialize(builder = FieldRecords.Builder.class) +public final class FieldRecords { private final Optional> fields; private final Optional> tokens; private final Map additionalProperties; - private V1FieldRecords( + private FieldRecords( Optional> fields, Optional> tokens, Map additionalProperties) { @@ -46,10 +51,10 @@ public Optional> getTokens() { return tokens; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof V1FieldRecords && equalTo((V1FieldRecords) other); + return other instanceof FieldRecords && equalTo((FieldRecords) other); } @JsonAnyGetter @@ -57,16 +62,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(V1FieldRecords other) { + private boolean equalTo(FieldRecords other) { return fields.equals(other.fields) && tokens.equals(other.tokens); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.fields, this.tokens); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -86,7 +91,7 @@ public static final class Builder { private Builder() {} - public Builder from(V1FieldRecords other) { + public Builder from(FieldRecords other) { fields(other.getFields()); tokens(other.getTokens()); return this; @@ -120,8 +125,18 @@ public Builder tokens(Map tokens) { return this; } - public V1FieldRecords build() { - return new V1FieldRecords(fields, tokens, additionalProperties); + public FieldRecords build() { + return new FieldRecords(fields, tokens, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileData.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileData.java deleted file mode 100644 index fd6fa822..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileData.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = FileData.Builder.class) -public final class FileData { - private final String base64; - - private final FileDataDataFormat dataFormat; - - private final Map additionalProperties; - - private FileData(String base64, FileDataDataFormat dataFormat, Map additionalProperties) { - this.base64 = base64; - this.dataFormat = dataFormat; - this.additionalProperties = additionalProperties; - } - - /** - * @return Base64-encoded data of the file. - */ - @JsonProperty("base64") - public String getBase64() { - return base64; - } - - /** - * @return Format of the file. - */ - @JsonProperty("data_format") - public FileDataDataFormat getDataFormat() { - return dataFormat; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof FileData && equalTo((FileData) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(FileData other) { - return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); - } - - @Override - public int hashCode() { - return Objects.hash(this.base64, this.dataFormat); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Base64Stage builder() { - return new Builder(); - } - - public interface Base64Stage { - /** - * Base64-encoded data of the file. - */ - DataFormatStage base64(@NotNull String base64); - - Builder from(FileData other); - } - - public interface DataFormatStage { - /** - * Format of the file. - */ - _FinalStage dataFormat(@NotNull FileDataDataFormat dataFormat); - } - - public interface _FinalStage { - FileData build(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { - private String base64; - - private FileDataDataFormat dataFormat; - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(FileData other) { - base64(other.getBase64()); - dataFormat(other.getDataFormat()); - return this; - } - - /** - * Base64-encoded data of the file.

                                  Base64-encoded data of the file.

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

                                  Format of the file.

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

                                  Base64-encoded data of the file.

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

                                  Format of the file.

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

                                  Base64-encoded data of the file.

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

                                  Format of the file.

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

                                  Base64-encoded data of the file.

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

                                  Format of the file.

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

                                  Base64-encoded data of the file.

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

                                  Base64-encoded data of the file.

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

                                  Format of the file.

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

                                  Base64-encoded data of the file.

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

                                  Format of the file.

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

                                  Base64-encoded data of the file.

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

                                  Format of the file.

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

                                  Base64-encoded data of the file.

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

                                  Base64-encoded data of the file.

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

                                  Format of the file.

                                  - * @return Reference to {@code this} so that method calls can be chained together. - */ - @Override - @JsonSetter("data_format") - public _FinalStage dataFormat(@NotNull FileDataReidentifyFileDataFormat dataFormat) { - this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); - return this; - } - - @Override - public FileDataReidentifyFile build() { - return new FileDataReidentifyFile(base64, dataFormat, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDataReidentifyFileDataFormat.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDataReidentifyFileDataFormat.java deleted file mode 100644 index cc8293d2..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDataReidentifyFileDataFormat.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum FileDataReidentifyFileDataFormat { - TXT("txt"), - - CSV("csv"), - - JSON("json"), - - XLS("xls"), - - XLSX("xlsx"), - - DOC("doc"), - - DOCX("docx"), - - XML("xml"); - - private final String value; - - FileDataReidentifyFileDataFormat(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteRecord.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteRecord.java new file mode 100644 index 00000000..5d3aad52 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteRecord.java @@ -0,0 +1,280 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileDeleteRecord.Builder.class) +public final class FileDeleteRecord { + private final String tableName; + + private final Optional skyflowId; + + private final List columns; + + private final Optional> uniqueValues; + + private final Map additionalProperties; + + private FileDeleteRecord( + String tableName, + Optional skyflowId, + List columns, + Optional> uniqueValues, + Map additionalProperties) { + this.tableName = tableName; + this.skyflowId = skyflowId; + this.columns = columns; + this.uniqueValues = uniqueValues; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the table. + */ + @JsonProperty("tableName") + public String getTableName() { + return tableName; + } + + /** + * @return Skyflow ID of the record containing the file column(s) to delete. Either skyflowID or uniqueValues must be specified, not both. + */ + @JsonProperty("skyflowID") + public Optional getSkyflowId() { + return skyflowId; + } + + /** + * @return Names of the file columns to delete on this record. If any listed column has no file present, the request fails for this record. + */ + @JsonProperty("columns") + public List getColumns() { + return columns; + } + + /** + * @return List of unique constraint values used to look up the record(s) to delete, in place of skyflowID. If more than one object is provided, each is resolved independently and the specified columns are deleted from every matching record. + */ + @JsonProperty("uniqueValues") + public Optional> getUniqueValues() { + return uniqueValues; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileDeleteRecord && equalTo((FileDeleteRecord) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileDeleteRecord other) { + return tableName.equals(other.tableName) + && skyflowId.equals(other.skyflowId) + && columns.equals(other.columns) + && uniqueValues.equals(other.uniqueValues); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tableName, this.skyflowId, this.columns, this.uniqueValues); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TableNameStage builder() { + return new Builder(); + } + + public interface TableNameStage { + /** + *

                                  Name of the table.

                                  + */ + _FinalStage tableName(@NotNull String tableName); + + Builder from(FileDeleteRecord other); + } + + public interface _FinalStage { + FileDeleteRecord build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Skyflow ID of the record containing the file column(s) to delete. Either skyflowID or uniqueValues must be specified, not both.

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

                                  Names of the file columns to delete on this record. If any listed column has no file present, the request fails for this record.

                                  + */ + _FinalStage columns(List columns); + + _FinalStage addColumns(String columns); + + _FinalStage addAllColumns(List columns); + + /** + *

                                  List of unique constraint values used to look up the record(s) to delete, in place of skyflowID. If more than one object is provided, each is resolved independently and the specified columns are deleted from every matching record.

                                  + */ + _FinalStage uniqueValues(Optional> uniqueValues); + + _FinalStage uniqueValues(List uniqueValues); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TableNameStage, _FinalStage { + private String tableName; + + private Optional> uniqueValues = Optional.empty(); + + private List columns = new ArrayList<>(); + + private Optional skyflowId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(FileDeleteRecord other) { + tableName(other.getTableName()); + skyflowId(other.getSkyflowId()); + columns(other.getColumns()); + uniqueValues(other.getUniqueValues()); + return this; + } + + /** + *

                                  Name of the table.

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

                                  List of unique constraint values used to look up the record(s) to delete, in place of skyflowID. If more than one object is provided, each is resolved independently and the specified columns are deleted from every matching record.

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

                                  List of unique constraint values used to look up the record(s) to delete, in place of skyflowID. If more than one object is provided, each is resolved independently and the specified columns are deleted from every matching record.

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

                                  Names of the file columns to delete on this record. If any listed column has no file present, the request fails for this record.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllColumns(List columns) { + if (columns != null) { + this.columns.addAll(columns); + } + return this; + } + + /** + *

                                  Names of the file columns to delete on this record. If any listed column has no file present, the request fails for this record.

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

                                  Names of the file columns to delete on this record. If any listed column has no file present, the request fails for this record.

                                  + */ + @java.lang.Override + @JsonSetter(value = "columns", nulls = Nulls.SKIP) + public _FinalStage columns(List columns) { + this.columns.clear(); + if (columns != null) { + this.columns.addAll(columns); + } + return this; + } + + /** + *

                                  Skyflow ID of the record containing the file column(s) to delete. Either skyflowID or uniqueValues must be specified, not both.

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

                                  Skyflow ID of the record containing the file column(s) to delete. Either skyflowID or uniqueValues must be specified, not both.

                                  + */ + @java.lang.Override + @JsonSetter(value = "skyflowID", nulls = Nulls.SKIP) + public _FinalStage skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + @java.lang.Override + public FileDeleteRecord build() { + return new FileDeleteRecord(tableName, skyflowId, columns, uniqueValues, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteResponse.java new file mode 100644 index 00000000..5062fdf2 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteResponse.java @@ -0,0 +1,122 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileDeleteResponse.Builder.class) +public final class FileDeleteResponse { + private final List records; + + private final Map additionalProperties; + + private FileDeleteResponse(List records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return List of records (max 100) with the result of the delete operation. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileDeleteResponse && equalTo((FileDeleteResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileDeleteResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(FileDeleteResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

                                  List of records (max 100) with the result of the delete operation.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(FileDeleteResponseObject records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public FileDeleteResponse build() { + return new FileDeleteResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteResponseObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteResponseObject.java new file mode 100644 index 00000000..61427130 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileDeleteResponseObject.java @@ -0,0 +1,295 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileDeleteResponseObject.Builder.class) +public final class FileDeleteResponseObject { + private final Optional skyflowId; + + private final String tableName; + + private final Optional> data; + + private final Optional error; + + private final int httpCode; + + private final Map additionalProperties; + + private FileDeleteResponseObject( + Optional skyflowId, + String tableName, + Optional> data, + Optional error, + int httpCode, + Map additionalProperties) { + this.skyflowId = skyflowId; + this.tableName = tableName; + this.data = data; + this.error = error; + this.httpCode = httpCode; + this.additionalProperties = additionalProperties; + } + + /** + * @return Skyflow ID of the record that was targeted. When the request specifies uniqueValues, this is the skyflowID resolved from the matching record. Null if the record failed validation before a skyflowID could be resolved. + */ + @JsonProperty("skyflowID") + public Optional getSkyflowId() { + return skyflowId; + } + + /** + * @return Name of the table. + */ + @JsonProperty("tableName") + public String getTableName() { + return tableName; + } + + /** + * @return Map of column name to deletion result. Populated only when the record's delete succeeds, with one entry per requested column with status DELETED. Null if any requested column has no file present, in which case error is populated instead. + */ + @JsonProperty("data") + public Optional> getData() { + return data; + } + + /** + * @return Error message describing any issue with the specific record. Null if no error occurred. + */ + @JsonProperty("error") + public Optional getError() { + return error; + } + + /** + * @return HTTP status code representing the result of the API request for this record. + */ + @JsonProperty("httpCode") + public int getHttpCode() { + return httpCode; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileDeleteResponseObject && equalTo((FileDeleteResponseObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileDeleteResponseObject other) { + return skyflowId.equals(other.skyflowId) + && tableName.equals(other.tableName) + && data.equals(other.data) + && error.equals(other.error) + && httpCode == other.httpCode; + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.tableName, this.data, this.error, this.httpCode); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TableNameStage builder() { + return new Builder(); + } + + public interface TableNameStage { + /** + *

                                  Name of the table.

                                  + */ + HttpCodeStage tableName(@NotNull String tableName); + + Builder from(FileDeleteResponseObject other); + } + + public interface HttpCodeStage { + /** + *

                                  HTTP status code representing the result of the API request for this record.

                                  + */ + _FinalStage httpCode(int httpCode); + } + + public interface _FinalStage { + FileDeleteResponseObject build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Skyflow ID of the record that was targeted. When the request specifies uniqueValues, this is the skyflowID resolved from the matching record. Null if the record failed validation before a skyflowID could be resolved.

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

                                  Map of column name to deletion result. Populated only when the record's delete succeeds, with one entry per requested column with status DELETED. Null if any requested column has no file present, in which case error is populated instead.

                                  + */ + _FinalStage data(Optional> data); + + _FinalStage data(Map data); + + /** + *

                                  Error message describing any issue with the specific record. Null if no error occurred.

                                  + */ + _FinalStage error(Optional error); + + _FinalStage error(String error); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TableNameStage, HttpCodeStage, _FinalStage { + private String tableName; + + private int httpCode; + + private Optional error = Optional.empty(); + + private Optional> data = Optional.empty(); + + private Optional skyflowId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(FileDeleteResponseObject other) { + skyflowId(other.getSkyflowId()); + tableName(other.getTableName()); + data(other.getData()); + error(other.getError()); + httpCode(other.getHttpCode()); + return this; + } + + /** + *

                                  Name of the table.

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

                                  HTTP status code representing the result of the API request for this record.

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

                                  Error message describing any issue with the specific record. Null if no error occurred.

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

                                  Error message describing any issue with the specific record. Null if no error occurred.

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

                                  Map of column name to deletion result. Populated only when the record's delete succeeds, with one entry per requested column with status DELETED. Null if any requested column has no file present, in which case error is populated instead.

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

                                  Map of column name to deletion result. Populated only when the record's delete succeeds, with one entry per requested column with status DELETED. Null if any requested column has no file present, in which case error is populated instead.

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

                                  Skyflow ID of the record that was targeted. When the request specifies uniqueValues, this is the skyflowID resolved from the matching record. Null if the record failed validation before a skyflowID could be resolved.

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

                                  Skyflow ID of the record that was targeted. When the request specifies uniqueValues, this is the skyflowID resolved from the matching record. Null if the record failed validation before a skyflowID could be resolved.

                                  + */ + @java.lang.Override + @JsonSetter(value = "skyflowID", nulls = Nulls.SKIP) + public _FinalStage skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + @java.lang.Override + public FileDeleteResponseObject build() { + return new FileDeleteResponseObject(skyflowId, tableName, data, error, httpCode, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileMetadata.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileMetadata.java new file mode 100644 index 00000000..ff30111e --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileMetadata.java @@ -0,0 +1,173 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileMetadata.Builder.class) +public final class FileMetadata { + private final Optional fileName; + + private final Optional fileSizeKb; + + private final Optional fileType; + + private final Map additionalProperties; + + private FileMetadata( + Optional fileName, + Optional fileSizeKb, + Optional fileType, + Map additionalProperties) { + this.fileName = fileName; + this.fileSizeKb = fileSizeKb; + this.fileType = fileType; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the file, including the extension if provided. + */ + @JsonProperty("fileName") + public Optional getFileName() { + return fileName; + } + + /** + * @return Size of the file in kilobytes (KB), rounded up from bytes to the nearest KB. + */ + @JsonProperty("fileSizeKB") + public Optional getFileSizeKb() { + return fileSizeKb; + } + + /** + * @return Type of the file, detected based on its content (MIME type). + */ + @JsonProperty("fileType") + public Optional getFileType() { + return fileType; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileMetadata && equalTo((FileMetadata) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileMetadata other) { + return fileName.equals(other.fileName) + && fileSizeKb.equals(other.fileSizeKb) + && fileType.equals(other.fileType); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.fileName, this.fileSizeKb, this.fileType); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional fileName = Optional.empty(); + + private Optional fileSizeKb = Optional.empty(); + + private Optional fileType = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(FileMetadata other) { + fileName(other.getFileName()); + fileSizeKb(other.getFileSizeKb()); + fileType(other.getFileType()); + return this; + } + + /** + *

                                  Name of the file, including the extension if provided.

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

                                  Size of the file in kilobytes (KB), rounded up from bytes to the nearest KB.

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

                                  Type of the file, detected based on its content (MIME type).

                                  + */ + @JsonSetter(value = "fileType", nulls = Nulls.SKIP) + public Builder fileType(Optional fileType) { + this.fileType = fileType; + return this; + } + + public Builder fileType(String fileType) { + this.fileType = Optional.ofNullable(fileType); + return this; + } + + public FileMetadata build() { + return new FileMetadata(fileName, fileSizeKb, fileType, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadColumn.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadColumn.java new file mode 100644 index 00000000..73d3f27e --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadColumn.java @@ -0,0 +1,171 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileUploadColumn.Builder.class) +public final class FileUploadColumn { + private final String column; + + private final Optional fileName; + + private final Map additionalProperties; + + private FileUploadColumn(String column, Optional fileName, Map additionalProperties) { + this.column = column; + this.fileName = fileName; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the column where the file is being uploaded. + */ + @JsonProperty("column") + public String getColumn() { + return column; + } + + /** + * @return Name of the file being uploaded to the file column. If not provided, a random 16-byte UUID name is generated. + */ + @JsonProperty("fileName") + public Optional getFileName() { + return fileName; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileUploadColumn && equalTo((FileUploadColumn) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileUploadColumn other) { + return column.equals(other.column) && fileName.equals(other.fileName); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.column, this.fileName); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ColumnStage builder() { + return new Builder(); + } + + public interface ColumnStage { + /** + *

                                  Name of the column where the file is being uploaded.

                                  + */ + _FinalStage column(@NotNull String column); + + Builder from(FileUploadColumn other); + } + + public interface _FinalStage { + FileUploadColumn build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Name of the file being uploaded to the file column. If not provided, a random 16-byte UUID name is generated.

                                  + */ + _FinalStage fileName(Optional fileName); + + _FinalStage fileName(String fileName); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ColumnStage, _FinalStage { + private String column; + + private Optional fileName = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(FileUploadColumn other) { + column(other.getColumn()); + fileName(other.getFileName()); + return this; + } + + /** + *

                                  Name of the column where the file is being uploaded.

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

                                  Name of the file being uploaded to the file column. If not provided, a random 16-byte UUID name is generated.

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

                                  Name of the file being uploaded to the file column. If not provided, a random 16-byte UUID name is generated.

                                  + */ + @java.lang.Override + @JsonSetter(value = "fileName", nulls = Nulls.SKIP) + public _FinalStage fileName(Optional fileName) { + this.fileName = fileName; + return this; + } + + @java.lang.Override + public FileUploadColumn build() { + return new FileUploadColumn(column, fileName, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadRecord.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadRecord.java new file mode 100644 index 00000000..976b0bfb --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadRecord.java @@ -0,0 +1,235 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileUploadRecord.Builder.class) +public final class FileUploadRecord { + private final String tableName; + + private final Optional skyflowId; + + private final List columns; + + private final Map additionalProperties; + + private FileUploadRecord( + String tableName, + Optional skyflowId, + List columns, + Map additionalProperties) { + this.tableName = tableName; + this.skyflowId = skyflowId; + this.columns = columns; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the table. + */ + @JsonProperty("tableName") + public String getTableName() { + return tableName; + } + + /** + * @return Skyflow ID of the record. If not provided, a new record is created and its skyflowID is used for the file upload. + */ + @JsonProperty("skyflowID") + public Optional getSkyflowId() { + return skyflowId; + } + + /** + * @return List of file columns to generate signed upload URLs for. + */ + @JsonProperty("columns") + public List getColumns() { + return columns; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileUploadRecord && equalTo((FileUploadRecord) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileUploadRecord other) { + return tableName.equals(other.tableName) && skyflowId.equals(other.skyflowId) && columns.equals(other.columns); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tableName, this.skyflowId, this.columns); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TableNameStage builder() { + return new Builder(); + } + + public interface TableNameStage { + /** + *

                                  Name of the table.

                                  + */ + _FinalStage tableName(@NotNull String tableName); + + Builder from(FileUploadRecord other); + } + + public interface _FinalStage { + FileUploadRecord build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Skyflow ID of the record. If not provided, a new record is created and its skyflowID is used for the file upload.

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

                                  List of file columns to generate signed upload URLs for.

                                  + */ + _FinalStage columns(List columns); + + _FinalStage addColumns(FileUploadColumn columns); + + _FinalStage addAllColumns(List columns); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TableNameStage, _FinalStage { + private String tableName; + + private List columns = new ArrayList<>(); + + private Optional skyflowId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(FileUploadRecord other) { + tableName(other.getTableName()); + skyflowId(other.getSkyflowId()); + columns(other.getColumns()); + return this; + } + + /** + *

                                  Name of the table.

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

                                  List of file columns to generate signed upload URLs for.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllColumns(List columns) { + if (columns != null) { + this.columns.addAll(columns); + } + return this; + } + + /** + *

                                  List of file columns to generate signed upload URLs for.

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

                                  List of file columns to generate signed upload URLs for.

                                  + */ + @java.lang.Override + @JsonSetter(value = "columns", nulls = Nulls.SKIP) + public _FinalStage columns(List columns) { + this.columns.clear(); + if (columns != null) { + this.columns.addAll(columns); + } + return this; + } + + /** + *

                                  Skyflow ID of the record. If not provided, a new record is created and its skyflowID is used for the file upload.

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

                                  Skyflow ID of the record. If not provided, a new record is created and its skyflowID is used for the file upload.

                                  + */ + @java.lang.Override + @JsonSetter(value = "skyflowID", nulls = Nulls.SKIP) + public _FinalStage skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + @java.lang.Override + public FileUploadRecord build() { + return new FileUploadRecord(tableName, skyflowId, columns, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadResponse.java new file mode 100644 index 00000000..6ef52d52 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadResponse.java @@ -0,0 +1,122 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileUploadResponse.Builder.class) +public final class FileUploadResponse { + private final List records; + + private final Map additionalProperties; + + private FileUploadResponse(List records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return List of records with signed upload URLs. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileUploadResponse && equalTo((FileUploadResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileUploadResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(FileUploadResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

                                  List of records with signed upload URLs.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(FileUploadResponseObject records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public FileUploadResponse build() { + return new FileUploadResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadResponseObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadResponseObject.java new file mode 100644 index 00000000..5a2d674c --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/FileUploadResponseObject.java @@ -0,0 +1,286 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileUploadResponseObject.Builder.class) +public final class FileUploadResponseObject { + private final String skyflowId; + + private final String tableName; + + private final Optional> data; + + private final Optional error; + + private final int httpCode; + + private final Map additionalProperties; + + private FileUploadResponseObject( + String skyflowId, + String tableName, + Optional> data, + Optional error, + int httpCode, + Map additionalProperties) { + this.skyflowId = skyflowId; + this.tableName = tableName; + this.data = data; + this.error = error; + this.httpCode = httpCode; + this.additionalProperties = additionalProperties; + } + + /** + * @return Skyflow ID of the record. A new skyflowID is returned if one was not provided in the request. + */ + @JsonProperty("skyflowID") + public String getSkyflowId() { + return skyflowId; + } + + /** + * @return Name of the table. + */ + @JsonProperty("tableName") + public String getTableName() { + return tableName; + } + + /** + * @return Map of column names to signed upload URLs. Each signed URL expires after 15 minutes by default. + */ + @JsonProperty("data") + public Optional> getData() { + return data; + } + + /** + * @return Error message describing any issue with the specific record. Null if no error occurred. + */ + @JsonProperty("error") + public Optional getError() { + return error; + } + + /** + * @return HTTP status code representing the result of the API request for this record. + */ + @JsonProperty("httpCode") + public int getHttpCode() { + return httpCode; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileUploadResponseObject && equalTo((FileUploadResponseObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(FileUploadResponseObject other) { + return skyflowId.equals(other.skyflowId) + && tableName.equals(other.tableName) + && data.equals(other.data) + && error.equals(other.error) + && httpCode == other.httpCode; + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.tableName, this.data, this.error, this.httpCode); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static SkyflowIdStage builder() { + return new Builder(); + } + + public interface SkyflowIdStage { + /** + *

                                  Skyflow ID of the record. A new skyflowID is returned if one was not provided in the request.

                                  + */ + TableNameStage skyflowId(@NotNull String skyflowId); + + Builder from(FileUploadResponseObject other); + } + + public interface TableNameStage { + /** + *

                                  Name of the table.

                                  + */ + HttpCodeStage tableName(@NotNull String tableName); + } + + public interface HttpCodeStage { + /** + *

                                  HTTP status code representing the result of the API request for this record.

                                  + */ + _FinalStage httpCode(int httpCode); + } + + public interface _FinalStage { + FileUploadResponseObject build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Map of column names to signed upload URLs. Each signed URL expires after 15 minutes by default.

                                  + */ + _FinalStage data(Optional> data); + + _FinalStage data(Map data); + + /** + *

                                  Error message describing any issue with the specific record. Null if no error occurred.

                                  + */ + _FinalStage error(Optional error); + + _FinalStage error(String error); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements SkyflowIdStage, TableNameStage, HttpCodeStage, _FinalStage { + private String skyflowId; + + private String tableName; + + private int httpCode; + + private Optional error = Optional.empty(); + + private Optional> data = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(FileUploadResponseObject other) { + skyflowId(other.getSkyflowId()); + tableName(other.getTableName()); + data(other.getData()); + error(other.getError()); + httpCode(other.getHttpCode()); + return this; + } + + /** + *

                                  Skyflow ID of the record. A new skyflowID is returned if one was not provided in the request.

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

                                  Name of the table.

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

                                  HTTP status code representing the result of the API request for this record.

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

                                  Error message describing any issue with the specific record. Null if no error occurred.

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

                                  Error message describing any issue with the specific record. Null if no error occurred.

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

                                  Map of column names to signed upload URLs. Each signed URL expires after 15 minutes by default.

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

                                  Map of column names to signed upload URLs. Each signed URL expires after 15 minutes by default.

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

                                  Entity types to fully redact.

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

                                  Entity types to mask.

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

                                  Entity types to return in plaintext.

                                  - */ - @JsonSetter(value = "plaintext", nulls = Nulls.SKIP) - public Builder plaintext(Optional> plaintext) { - this.plaintext = plaintext; - return this; - } - - public Builder plaintext(List plaintext) { - this.plaintext = Optional.ofNullable(plaintext); - return this; - } - - public Format build() { - return new Format(redacted, masked, plaintext, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatMaskedItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatMaskedItem.java deleted file mode 100644 index 77d18a2b..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatMaskedItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum FormatMaskedItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - FormatMaskedItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatPlaintextItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatPlaintextItem.java deleted file mode 100644 index 0a5e97f8..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatPlaintextItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum FormatPlaintextItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - FormatPlaintextItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatRedactedItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatRedactedItem.java deleted file mode 100644 index 92eb291a..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/FormatRedactedItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum FormatRedactedItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - FormatRedactedItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/GetFieldRecords.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetFieldRecords.java new file mode 100644 index 00000000..230ddbbc --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetFieldRecords.java @@ -0,0 +1,171 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetFieldRecords.Builder.class) +public final class GetFieldRecords { + private final Optional> fields; + + private final Optional> tokens; + + private final Optional> fileMetadata; + + private final Map additionalProperties; + + private GetFieldRecords( + Optional> fields, + Optional> tokens, + Optional> fileMetadata, + Map additionalProperties) { + this.fields = fields; + this.tokens = tokens; + this.fileMetadata = fileMetadata; + this.additionalProperties = additionalProperties; + } + + /** + * @return Fields and values for the record. For example, {'field_1':'value_1', 'field_2':'value_2'}. + */ + @JsonProperty("fields") + public Optional> getFields() { + return fields; + } + + /** + * @return Fields and tokens for the record. For example, {'field_1':'token_1', 'field_2':'token_2'}. + */ + @JsonProperty("tokens") + public Optional> getTokens() { + return tokens; + } + + /** + * @return Metadata for the uploaded file, keyed by dynamic column name. + */ + @JsonProperty("fileMetadata") + public Optional> getFileMetadata() { + return fileMetadata; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetFieldRecords && equalTo((GetFieldRecords) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetFieldRecords other) { + return fields.equals(other.fields) && tokens.equals(other.tokens) && fileMetadata.equals(other.fileMetadata); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.fields, this.tokens, this.fileMetadata); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> fields = Optional.empty(); + + private Optional> tokens = Optional.empty(); + + private Optional> fileMetadata = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(GetFieldRecords other) { + fields(other.getFields()); + tokens(other.getTokens()); + fileMetadata(other.getFileMetadata()); + return this; + } + + /** + *

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

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

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

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

                                  Metadata for the uploaded file, keyed by dynamic column name.

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

                                  Records returned by the query.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + public GetQueryResponse build() { + return new GetQueryResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/GetRequestData.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetRequestData.java new file mode 100644 index 00000000..dbe46db3 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetRequestData.java @@ -0,0 +1,324 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetRequestData.Builder.class) +public final class GetRequestData { + private final String tableName; + + private final List skyflowIDs; + + private final Optional> columnRedactions; + + private final Optional> columns; + + private final Optional> uniqueValues; + + private final Map additionalProperties; + + private GetRequestData( + String tableName, + List skyflowIDs, + Optional> columnRedactions, + Optional> columns, + Optional> uniqueValues, + Map additionalProperties) { + this.tableName = tableName; + this.skyflowIDs = skyflowIDs; + this.columnRedactions = columnRedactions; + this.columns = columns; + this.uniqueValues = uniqueValues; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the table. + */ + @JsonProperty("tableName") + public String getTableName() { + return tableName; + } + + /** + * @return Skyflow IDs of the records to return. + */ + @JsonProperty("skyflowIDs") + public List getSkyflowIDs() { + return skyflowIDs; + } + + /** + * @return List of columns to redact. + */ + @JsonProperty("columnRedactions") + public Optional> getColumnRedactions() { + return columnRedactions; + } + + /** + * @return List of columns to return. + */ + @JsonProperty("columns") + public Optional> getColumns() { + return columns; + } + + /** + * @return List of unique constraint values to query records by data. + */ + @JsonProperty("uniqueValues") + public Optional> getUniqueValues() { + return uniqueValues; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetRequestData && equalTo((GetRequestData) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetRequestData other) { + return tableName.equals(other.tableName) + && skyflowIDs.equals(other.skyflowIDs) + && columnRedactions.equals(other.columnRedactions) + && columns.equals(other.columns) + && uniqueValues.equals(other.uniqueValues); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tableName, this.skyflowIDs, this.columnRedactions, this.columns, this.uniqueValues); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TableNameStage builder() { + return new Builder(); + } + + public interface TableNameStage { + /** + *

                                  Name of the table.

                                  + */ + _FinalStage tableName(@NotNull String tableName); + + Builder from(GetRequestData other); + } + + public interface _FinalStage { + GetRequestData build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Skyflow IDs of the records to return.

                                  + */ + _FinalStage skyflowIDs(List skyflowIDs); + + _FinalStage addSkyflowIDs(String skyflowIDs); + + _FinalStage addAllSkyflowIDs(List skyflowIDs); + + /** + *

                                  List of columns to redact.

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

                                  List of columns to return.

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

                                  List of unique constraint values to query records by data.

                                  + */ + _FinalStage uniqueValues(Optional> uniqueValues); + + _FinalStage uniqueValues(List uniqueValues); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TableNameStage, _FinalStage { + private String tableName; + + private Optional> uniqueValues = Optional.empty(); + + private Optional> columns = Optional.empty(); + + private Optional> columnRedactions = Optional.empty(); + + private List skyflowIDs = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(GetRequestData other) { + tableName(other.getTableName()); + skyflowIDs(other.getSkyflowIDs()); + columnRedactions(other.getColumnRedactions()); + columns(other.getColumns()); + uniqueValues(other.getUniqueValues()); + return this; + } + + /** + *

                                  Name of the table.

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

                                  List of unique constraint values to query records by data.

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

                                  List of unique constraint values to query records by data.

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

                                  List of columns to return.

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

                                  List of columns to return.

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

                                  List of columns to redact.

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

                                  List of columns to redact.

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

                                  Skyflow IDs of the records to return.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllSkyflowIDs(List skyflowIDs) { + if (skyflowIDs != null) { + this.skyflowIDs.addAll(skyflowIDs); + } + return this; + } + + /** + *

                                  Skyflow IDs of the records to return.

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

                                  Skyflow IDs of the records to return.

                                  + */ + @java.lang.Override + @JsonSetter(value = "skyflowIDs", nulls = Nulls.SKIP) + public _FinalStage skyflowIDs(List skyflowIDs) { + this.skyflowIDs.clear(); + if (skyflowIDs != null) { + this.skyflowIDs.addAll(skyflowIDs); + } + return this; + } + + @java.lang.Override + public GetRequestData build() { + return new GetRequestData( + tableName, skyflowIDs, columnRedactions, columns, uniqueValues, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/GetResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetResponse.java new file mode 100644 index 00000000..fa49bbb4 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetResponse.java @@ -0,0 +1,122 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetResponse.Builder.class) +public final class GetResponse { + private final List records; + + private final Map additionalProperties; + + private GetResponse(List records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return List of fetched records. For file columns, the value in the data map is an object containing: fileName, mimeType, sizeBytes, fileStatus (PENDING | READY | FAILED | SCAN_ERROR), fileFailureReason (non-null only when fileStatus is FAILED), url (pre-signed download URL, non-null only when fileStatus is READY), and urlExpiresAt (UTC expiry of the URL). + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetResponse && equalTo((GetResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(GetResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

                                  List of fetched records. For file columns, the value in the data map is an object containing: fileName, mimeType, sizeBytes, fileStatus (PENDING | READY | FAILED | SCAN_ERROR), fileFailureReason (non-null only when fileStatus is FAILED), url (pre-signed download URL, non-null only when fileStatus is READY), and urlExpiresAt (UTC expiry of the URL).

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(RecordResponseObject records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public GetResponse build() { + return new GetResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/GetTokensFromValuesRequestObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetTokensFromValuesRequestObject.java new file mode 100644 index 00000000..c0fab010 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetTokensFromValuesRequestObject.java @@ -0,0 +1,151 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetTokensFromValuesRequestObject.Builder.class) +public final class GetTokensFromValuesRequestObject { + private final GoogleProtobufValue value; + + private final String tokenGroupName; + + private final Map additionalProperties; + + private GetTokensFromValuesRequestObject( + GoogleProtobufValue value, String tokenGroupName, Map additionalProperties) { + this.value = value; + this.tokenGroupName = tokenGroupName; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("value") + public GoogleProtobufValue getValue() { + return value; + } + + /** + * @return Name of the deterministic token group. + */ + @JsonProperty("tokenGroupName") + public String getTokenGroupName() { + return tokenGroupName; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetTokensFromValuesRequestObject && equalTo((GetTokensFromValuesRequestObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetTokensFromValuesRequestObject other) { + return value.equals(other.value) && tokenGroupName.equals(other.tokenGroupName); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value, this.tokenGroupName); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ValueStage builder() { + return new Builder(); + } + + public interface ValueStage { + TokenGroupNameStage value(@NotNull GoogleProtobufValue value); + + Builder from(GetTokensFromValuesRequestObject other); + } + + public interface TokenGroupNameStage { + /** + *

                                  Name of the deterministic token group.

                                  + */ + _FinalStage tokenGroupName(@NotNull String tokenGroupName); + } + + public interface _FinalStage { + GetTokensFromValuesRequestObject build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ValueStage, TokenGroupNameStage, _FinalStage { + private GoogleProtobufValue value; + + private String tokenGroupName; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(GetTokensFromValuesRequestObject other) { + value(other.getValue()); + tokenGroupName(other.getTokenGroupName()); + return this; + } + + @java.lang.Override + @JsonSetter("value") + public TokenGroupNameStage value(@NotNull GoogleProtobufValue value) { + this.value = Objects.requireNonNull(value, "value must not be null"); + return this; + } + + /** + *

                                  Name of the deterministic token group.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("tokenGroupName") + public _FinalStage tokenGroupName(@NotNull String tokenGroupName) { + this.tokenGroupName = Objects.requireNonNull(tokenGroupName, "tokenGroupName must not be null"); + return this; + } + + @java.lang.Override + public GetTokensFromValuesRequestObject build() { + return new GetTokensFromValuesRequestObject(value, tokenGroupName, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/GetTokensFromValuesResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetTokensFromValuesResponse.java new file mode 100644 index 00000000..de800b47 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/GetTokensFromValuesResponse.java @@ -0,0 +1,123 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetTokensFromValuesResponse.Builder.class) +public final class GetTokensFromValuesResponse { + private final List records; + + private final Map additionalProperties; + + private GetTokensFromValuesResponse( + List records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return Array of token result objects, one per input entry, in the same order as the request. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetTokensFromValuesResponse && equalTo((GetTokensFromValuesResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetTokensFromValuesResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(GetTokensFromValuesResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

                                  Array of token result objects, one per input entry, in the same order as the request.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(TokenizeResponseObject records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public GetTokensFromValuesResponse build() { + return new GetTokensFromValuesResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/GoogleProtobufValue.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/GoogleProtobufValue.java new file mode 100644 index 00000000..0b0efc95 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/GoogleProtobufValue.java @@ -0,0 +1,42 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.skyflow.generated.rest.core.WrappedAlias; + +public final class GoogleProtobufValue implements WrappedAlias { + private final Object value; + + private GoogleProtobufValue(Object value) { + this.value = value; + } + + @JsonValue + public Object get() { + return this.value; + } + + @java.lang.Override + public boolean equals(Object other) { + return this == other + || (other instanceof GoogleProtobufValue && this.value.equals(((GoogleProtobufValue) other).value)); + } + + @java.lang.Override + public int hashCode() { + return value.hashCode(); + } + + @java.lang.Override + public String toString() { + return value.toString(); + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static GoogleProtobufValue of(Object value) { + return new GoogleProtobufValue(value); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java deleted file mode 100644 index 55be5699..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = GooglerpcStatus.Builder.class) -public final class GooglerpcStatus { - private final Optional code; - - private final Optional message; - - private final Optional> details; - - private final Map additionalProperties; - - private GooglerpcStatus( - Optional code, - Optional message, - Optional> details, - Map additionalProperties) { - this.code = code; - this.message = message; - this.details = details; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("code") - public Optional getCode() { - return code; - } - - @JsonProperty("message") - public Optional getMessage() { - return message; - } - - @JsonProperty("details") - public Optional> getDetails() { - return details; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof GooglerpcStatus && equalTo((GooglerpcStatus) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(GooglerpcStatus other) { - return code.equals(other.code) && message.equals(other.message) && details.equals(other.details); - } - - @Override - public int hashCode() { - return Objects.hash(this.code, this.message, this.details); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional code = Optional.empty(); - - private Optional message = Optional.empty(); - - private Optional> details = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(GooglerpcStatus other) { - code(other.getCode()); - message(other.getMessage()); - details(other.getDetails()); - return this; - } - - @JsonSetter(value = "code", nulls = Nulls.SKIP) - public Builder code(Optional code) { - this.code = code; - return this; - } - - public Builder code(Integer code) { - this.code = Optional.ofNullable(code); - return this; - } - - @JsonSetter(value = "message", nulls = Nulls.SKIP) - public Builder message(Optional message) { - this.message = message; - return this; - } - - public Builder message(String message) { - this.message = Optional.ofNullable(message); - return this; - } - - @JsonSetter(value = "details", nulls = Nulls.SKIP) - public Builder details(Optional> details) { - this.details = details; - return this; - } - - public Builder details(List details) { - this.details = Optional.ofNullable(details); - return this; - } - - public GooglerpcStatus build() { - return new GooglerpcStatus(code, message, details, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/IdentifyResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/IdentifyResponse.java deleted file mode 100644 index c1bd23c6..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/IdentifyResponse.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = IdentifyResponse.Builder.class) -public final class IdentifyResponse { - private final String text; - - private final Map additionalProperties; - - private IdentifyResponse(String text, Map additionalProperties) { - this.text = text; - this.additionalProperties = additionalProperties; - } - - /** - * @return Re-identified text. - */ - @JsonProperty("text") - public String getText() { - return text; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof IdentifyResponse && equalTo((IdentifyResponse) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(IdentifyResponse other) { - return text.equals(other.text); - } - - @Override - public int hashCode() { - return Objects.hash(this.text); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static TextStage builder() { - return new Builder(); - } - - public interface TextStage { - /** - * Re-identified text. - */ - _FinalStage text(@NotNull String text); - - Builder from(IdentifyResponse other); - } - - public interface _FinalStage { - IdentifyResponse build(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements TextStage, _FinalStage { - private String text; - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @Override - public Builder from(IdentifyResponse other) { - text(other.getText()); - return this; - } - - /** - * Re-identified text.

                                  Re-identified text.

                                  - * @return Reference to {@code this} so that method calls can be chained together. - */ - @Override - @JsonSetter("text") - public _FinalStage text(@NotNull String text) { - this.text = Objects.requireNonNull(text, "text must not be null"); - return this; - } - - @Override - public IdentifyResponse build() { - return new IdentifyResponse(text, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/InsertRecordData.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/InsertRecordData.java new file mode 100644 index 00000000..0b0ea516 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/InsertRecordData.java @@ -0,0 +1,176 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = InsertRecordData.Builder.class) +public final class InsertRecordData { + private final Map data; + + private final Optional tableName; + + private final Optional upsert; + + private final Map additionalProperties; + + private InsertRecordData( + Map data, + Optional tableName, + Optional upsert, + Map additionalProperties) { + this.data = data; + this.tableName = tableName; + this.upsert = upsert; + this.additionalProperties = additionalProperties; + } + + /** + * @return Columns and values for the record. + */ + @JsonProperty("data") + public Map getData() { + return data; + } + + /** + * @return Name of the table to insert data into. + */ + @JsonProperty("tableName") + public Optional getTableName() { + return tableName; + } + + @JsonProperty("upsert") + public Optional getUpsert() { + return upsert; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof InsertRecordData && equalTo((InsertRecordData) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(InsertRecordData other) { + return data.equals(other.data) && tableName.equals(other.tableName) && upsert.equals(other.upsert); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.data, this.tableName, this.upsert); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Map data = new LinkedHashMap<>(); + + private Optional tableName = Optional.empty(); + + private Optional upsert = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(InsertRecordData other) { + data(other.getData()); + tableName(other.getTableName()); + upsert(other.getUpsert()); + return this; + } + + /** + *

                                  Columns and values for the record.

                                  + */ + @JsonSetter(value = "data", nulls = Nulls.SKIP) + public Builder data(Map data) { + this.data.clear(); + if (data != null) { + this.data.putAll(data); + } + return this; + } + + public Builder putAllData(Map data) { + if (data != null) { + this.data.putAll(data); + } + return this; + } + + public Builder data(String key, Object value) { + this.data.put(key, value); + return this; + } + + /** + *

                                  Name of the table to insert data into.

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

                                  Inserted records.

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

                                  List of inserted records.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(RecordResponseObject records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public InsertResponse build() { + return new InsertResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java deleted file mode 100644 index 40e73b99..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = ProtobufAny.Builder.class) -public final class ProtobufAny { - private final Optional type; - - private final Map additionalProperties; - - private ProtobufAny(Optional type, Map additionalProperties) { - this.type = type; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("@type") - public Optional getType() { - return type; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof ProtobufAny && equalTo((ProtobufAny) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(ProtobufAny other) { - return type.equals(other.type); - } - - @Override - public int hashCode() { - return Objects.hash(this.type); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional type = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(ProtobufAny other) { - type(other.getType()); - return this; - } - - @JsonSetter(value = "@type", nulls = Nulls.SKIP) - public Builder type(Optional type) { - this.type = type; - return this; - } - - public Builder type(String type) { - this.type = Optional.ofNullable(type); - return this; - } - - public ProtobufAny build() { - return new ProtobufAny(type, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1RecordMetaProperties.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/RecordMetaProperties.java similarity index 70% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/V1RecordMetaProperties.java rename to skyvault/src/main/java/com/skyflow/generated/rest/types/RecordMetaProperties.java index 17f77df6..d6c890d5 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1RecordMetaProperties.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/RecordMetaProperties.java @@ -3,25 +3,30 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; - import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1RecordMetaProperties.Builder.class) -public final class V1RecordMetaProperties { +@JsonDeserialize(builder = RecordMetaProperties.Builder.class) +public final class RecordMetaProperties { private final Optional skyflowId; private final Optional> tokens; private final Map additionalProperties; - private V1RecordMetaProperties( + private RecordMetaProperties( Optional skyflowId, Optional> tokens, Map additionalProperties) { @@ -46,10 +51,10 @@ public Optional> getTokens() { return tokens; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof V1RecordMetaProperties && equalTo((V1RecordMetaProperties) other); + return other instanceof RecordMetaProperties && equalTo((RecordMetaProperties) other); } @JsonAnyGetter @@ -57,16 +62,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(V1RecordMetaProperties other) { + private boolean equalTo(RecordMetaProperties other) { return skyflowId.equals(other.skyflowId) && tokens.equals(other.tokens); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.skyflowId, this.tokens); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -86,7 +91,7 @@ public static final class Builder { private Builder() {} - public Builder from(V1RecordMetaProperties other) { + public Builder from(RecordMetaProperties other) { skyflowId(other.getSkyflowId()); tokens(other.getTokens()); return this; @@ -120,8 +125,18 @@ public Builder tokens(Map tokens) { return this; } - public V1RecordMetaProperties build() { - return new V1RecordMetaProperties(skyflowId, tokens, additionalProperties); + public RecordMetaProperties build() { + return new RecordMetaProperties(skyflowId, tokens, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/RecordResponseObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/RecordResponseObject.java new file mode 100644 index 00000000..a00428e2 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/RecordResponseObject.java @@ -0,0 +1,448 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.Nullable; +import com.skyflow.generated.rest.core.NullableNonemptyFilter; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RecordResponseObject.Builder.class) +public final class RecordResponseObject { + private final Optional skyflowId; + + private final Optional> tokens; + + private final Optional> data; + + private final Optional> hashedData; + + private final Optional error; + + private final int httpCode; + + private final Optional tableName; + + private final Map additionalProperties; + + private RecordResponseObject( + Optional skyflowId, + Optional> tokens, + Optional> data, + Optional> hashedData, + Optional error, + int httpCode, + Optional tableName, + Map additionalProperties) { + this.skyflowId = skyflowId; + this.tokens = tokens; + this.data = data; + this.hashedData = hashedData; + this.error = error; + this.httpCode = httpCode; + this.tableName = tableName; + this.additionalProperties = additionalProperties; + } + + /** + * @return Skyflow ID for the inserted record + */ + @JsonIgnore + public Optional getSkyflowId() { + if (skyflowId == null) { + return Optional.empty(); + } + return skyflowId; + } + + /** + * @return Columns and tokens for the record. + */ + @JsonProperty("tokens") + public Optional> getTokens() { + return tokens; + } + + /** + * @return Columns and values for the record. For file columns, the value is an object containing file metadata: fileName, mimeType, sizeBytes, fileStatus (PENDING | READY | FAILED | SCAN_ERROR), fileFailureReason (populated only when fileStatus is FAILED), url (pre-signed download URL, populated only when fileStatus is READY), and urlExpiresAt (UTC expiry of the URL). + */ + @JsonProperty("data") + public Optional> getData() { + return data; + } + + /** + * @return Columns and hashed values for the record. + */ + @JsonProperty("hashedData") + public Optional> getHashedData() { + return hashedData; + } + + /** + * @return Error message, if any. + */ + @JsonIgnore + public Optional getError() { + if (error == null) { + return Optional.empty(); + } + return error; + } + + /** + * @return HTTP status code of the response. + */ + @JsonProperty("httpCode") + public int getHttpCode() { + return httpCode; + } + + /** + * @return Name of the table that the record belongs to. + */ + @JsonProperty("tableName") + public Optional getTableName() { + return tableName; + } + + @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = NullableNonemptyFilter.class) + @JsonProperty("skyflowID") + private Optional _getSkyflowId() { + return skyflowId; + } + + @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = NullableNonemptyFilter.class) + @JsonProperty("error") + private Optional _getError() { + return error; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RecordResponseObject && equalTo((RecordResponseObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RecordResponseObject other) { + return skyflowId.equals(other.skyflowId) + && tokens.equals(other.tokens) + && data.equals(other.data) + && hashedData.equals(other.hashedData) + && error.equals(other.error) + && httpCode == other.httpCode + && tableName.equals(other.tableName); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.skyflowId, this.tokens, this.data, this.hashedData, this.error, this.httpCode, this.tableName); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static HttpCodeStage builder() { + return new Builder(); + } + + public interface HttpCodeStage { + /** + *

                                  HTTP status code of the response.

                                  + */ + _FinalStage httpCode(int httpCode); + + Builder from(RecordResponseObject other); + } + + public interface _FinalStage { + RecordResponseObject build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Skyflow ID for the inserted record

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

                                  Columns and tokens for the record.

                                  + */ + _FinalStage tokens(Optional> tokens); + + _FinalStage tokens(Map tokens); + + /** + *

                                  Columns and values for the record. For file columns, the value is an object containing file metadata: fileName, mimeType, sizeBytes, fileStatus (PENDING | READY | FAILED | SCAN_ERROR), fileFailureReason (populated only when fileStatus is FAILED), url (pre-signed download URL, populated only when fileStatus is READY), and urlExpiresAt (UTC expiry of the URL).

                                  + */ + _FinalStage data(Optional> data); + + _FinalStage data(Map data); + + /** + *

                                  Columns and hashed values for the record.

                                  + */ + _FinalStage hashedData(Optional> hashedData); + + _FinalStage hashedData(Map hashedData); + + /** + *

                                  Error message, if any.

                                  + */ + _FinalStage error(Optional error); + + _FinalStage error(String error); + + _FinalStage error(Nullable error); + + /** + *

                                  Name of the table that the record belongs to.

                                  + */ + _FinalStage tableName(Optional tableName); + + _FinalStage tableName(String tableName); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements HttpCodeStage, _FinalStage { + private int httpCode; + + private Optional tableName = Optional.empty(); + + private Optional error = Optional.empty(); + + private Optional> hashedData = Optional.empty(); + + private Optional> data = Optional.empty(); + + private Optional> tokens = Optional.empty(); + + private Optional skyflowId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(RecordResponseObject other) { + skyflowId(other.getSkyflowId()); + tokens(other.getTokens()); + data(other.getData()); + hashedData(other.getHashedData()); + error(other.getError()); + httpCode(other.getHttpCode()); + tableName(other.getTableName()); + return this; + } + + /** + *

                                  HTTP status code of the response.

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

                                  Name of the table that the record belongs to.

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

                                  Name of the table that the record belongs to.

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

                                  Error message, if any.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage error(Nullable error) { + if (error.isNull()) { + this.error = null; + } else if (error.isEmpty()) { + this.error = Optional.empty(); + } else { + this.error = Optional.of(error.get()); + } + return this; + } + + /** + *

                                  Error message, if any.

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

                                  Error message, if any.

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

                                  Columns and hashed values for the record.

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

                                  Columns and hashed values for the record.

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

                                  Columns and values for the record. For file columns, the value is an object containing file metadata: fileName, mimeType, sizeBytes, fileStatus (PENDING | READY | FAILED | SCAN_ERROR), fileFailureReason (populated only when fileStatus is FAILED), url (pre-signed download URL, populated only when fileStatus is READY), and urlExpiresAt (UTC expiry of the URL).

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

                                  Columns and values for the record. For file columns, the value is an object containing file metadata: fileName, mimeType, sizeBytes, fileStatus (PENDING | READY | FAILED | SCAN_ERROR), fileFailureReason (populated only when fileStatus is FAILED), url (pre-signed download URL, populated only when fileStatus is READY), and urlExpiresAt (UTC expiry of the URL).

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

                                  Columns and tokens for the record.

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

                                  Columns and tokens for the record.

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

                                  Skyflow ID for the inserted record

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage skyflowId(Nullable skyflowId) { + if (skyflowId.isNull()) { + this.skyflowId = null; + } else if (skyflowId.isEmpty()) { + this.skyflowId = Optional.empty(); + } else { + this.skyflowId = Optional.of(skyflowId.get()); + } + return this; + } + + /** + *

                                  Skyflow ID for the inserted record

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

                                  Skyflow ID for the inserted record

                                  + */ + @java.lang.Override + @JsonSetter(value = "skyflowID", nulls = Nulls.SKIP) + public _FinalStage skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + @java.lang.Override + public RecordResponseObject build() { + return new RecordResponseObject( + skyflowId, tokens, data, hashedData, error, httpCode, tableName, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifiedFileOutput.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifiedFileOutput.java deleted file mode 100644 index a12660cb..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifiedFileOutput.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = ReidentifiedFileOutput.Builder.class) -public final class ReidentifiedFileOutput { - private final Optional processedFile; - - private final Optional processedFileType; - - private final Optional processedFileExtension; - - private final Map additionalProperties; - - private ReidentifiedFileOutput( - Optional processedFile, - Optional processedFileType, - Optional processedFileExtension, - Map additionalProperties) { - this.processedFile = processedFile; - this.processedFileType = processedFileType; - this.processedFileExtension = processedFileExtension; - this.additionalProperties = additionalProperties; - } - - /** - * @return File content in Base64 format. - */ - @JsonProperty("processed_file") - public Optional getProcessedFile() { - return processedFile; - } - - /** - * @return Type of the processed file. - */ - @JsonProperty("processed_file_type") - public Optional getProcessedFileType() { - return processedFileType; - } - - /** - * @return Extension of the processed file. - */ - @JsonProperty("processed_file_extension") - public Optional getProcessedFileExtension() { - return processedFileExtension; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof ReidentifiedFileOutput && equalTo((ReidentifiedFileOutput) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(ReidentifiedFileOutput other) { - return processedFile.equals(other.processedFile) - && processedFileType.equals(other.processedFileType) - && processedFileExtension.equals(other.processedFileExtension); - } - - @Override - public int hashCode() { - return Objects.hash(this.processedFile, this.processedFileType, this.processedFileExtension); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional processedFile = Optional.empty(); - - private Optional processedFileType = Optional.empty(); - - private Optional processedFileExtension = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(ReidentifiedFileOutput other) { - processedFile(other.getProcessedFile()); - processedFileType(other.getProcessedFileType()); - processedFileExtension(other.getProcessedFileExtension()); - return this; - } - - /** - *

                                  File content in Base64 format.

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

                                  Type of the processed file.

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

                                  Extension of the processed file.

                                  - */ - @JsonSetter(value = "processed_file_extension", nulls = Nulls.SKIP) - public Builder processedFileExtension( - Optional processedFileExtension) { - this.processedFileExtension = processedFileExtension; - return this; - } - - public Builder processedFileExtension(ReidentifiedFileOutputProcessedFileExtension processedFileExtension) { - this.processedFileExtension = Optional.ofNullable(processedFileExtension); - return this; - } - - public ReidentifiedFileOutput build() { - return new ReidentifiedFileOutput( - processedFile, processedFileType, processedFileExtension, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifiedFileOutputProcessedFileExtension.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifiedFileOutputProcessedFileExtension.java deleted file mode 100644 index b99612e2..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifiedFileOutputProcessedFileExtension.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum ReidentifiedFileOutputProcessedFileExtension { - MP_3("mp3"), - - WAV("wav"), - - PDF("pdf"), - - TXT("txt"), - - CSV("csv"), - - JSON("json"), - - JPG("jpg"), - - JPEG("jpeg"), - - TIF("tif"), - - TIFF("tiff"), - - PNG("png"), - - BMP("bmp"), - - XLS("xls"), - - XLSX("xlsx"), - - DOC("doc"), - - DOCX("docx"), - - PPT("ppt"), - - PPTX("pptx"), - - XML("xml"), - - DCM("dcm"); - - private final String value; - - ReidentifiedFileOutputProcessedFileExtension(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java deleted file mode 100644 index b7bc22ca..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java +++ /dev/null @@ -1,150 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = ReidentifyFileResponse.Builder.class) -public final class ReidentifyFileResponse { - private final Optional status; - - private final Optional outputType; - - private final Optional output; - - private final Map additionalProperties; - - private ReidentifyFileResponse( - Optional status, - Optional outputType, - Optional output, - Map additionalProperties) { - this.status = status; - this.outputType = outputType; - this.output = output; - this.additionalProperties = additionalProperties; - } - - /** - * @return Status of the operation. - */ - @JsonProperty("status") - public Optional getStatus() { - return status; - } - - /** - * @return Format of the output file. - */ - @JsonProperty("output_type") - public Optional getOutputType() { - return outputType; - } - - @JsonProperty("output") - public Optional getOutput() { - return output; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof ReidentifyFileResponse && equalTo((ReidentifyFileResponse) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(ReidentifyFileResponse other) { - return status.equals(other.status) && outputType.equals(other.outputType) && output.equals(other.output); - } - - @Override - public int hashCode() { - return Objects.hash(this.status, this.outputType, this.output); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional status = Optional.empty(); - - private Optional outputType = Optional.empty(); - - private Optional output = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(ReidentifyFileResponse other) { - status(other.getStatus()); - outputType(other.getOutputType()); - output(other.getOutput()); - return this; - } - - /** - *

                                  Status of the operation.

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

                                  Format of the output file.

                                  - */ - @JsonSetter(value = "output_type", nulls = Nulls.SKIP) - public Builder outputType(Optional outputType) { - this.outputType = outputType; - return this; - } - - public Builder outputType(ReidentifyFileResponseOutputType outputType) { - this.outputType = Optional.ofNullable(outputType); - return this; - } - - @JsonSetter(value = "output", nulls = Nulls.SKIP) - public Builder output(Optional output) { - this.output = output; - return this; - } - - public Builder output(ReidentifiedFileOutput output) { - this.output = Optional.ofNullable(output); - return this; - } - - public ReidentifyFileResponse build() { - return new ReidentifyFileResponse(status, outputType, output, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java deleted file mode 100644 index 342e3d93..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum ReidentifyFileResponseOutputType { - UNKNOWN("UNKNOWN"), - - BASE_64("BASE64"); - - private final String value; - - ReidentifyFileResponseOutputType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java deleted file mode 100644 index 2b6aaa85..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum ReidentifyFileResponseStatus { - UNKNOWN("UNKNOWN"), - - FAILED("FAILED"), - - SUCCESS("SUCCESS"), - - IN_PROGRESS("IN_PROGRESS"); - - private final String value; - - ReidentifyFileResponseStatus(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/RequestActionType.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/RequestActionType.java deleted file mode 100644 index ad0a32a7..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/RequestActionType.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum RequestActionType { - NONE("NONE"), - - ASSIGN("ASSIGN"), - - CREATE("CREATE"), - - DELETE("DELETE"), - - EXECUTE("EXECUTE"), - - LIST("LIST"), - - READ("READ"), - - UNASSIGN("UNASSIGN"), - - UPDATE("UPDATE"), - - VALIDATE("VALIDATE"), - - LOGIN("LOGIN"), - - ROTATE("ROTATE"), - - SCHEDULEROTATION("SCHEDULEROTATION"), - - SCHEDULEROTATIONALERT("SCHEDULEROTATIONALERT"), - - IMPORT("IMPORT"), - - GETIMPORTPARAMETERS("GETIMPORTPARAMETERS"), - - PING("PING"), - - GETCLOUDPROVIDER("GETCLOUDPROVIDER"); - - private final String value; - - RequestActionType(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/ShiftDatesEntityTypesItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/ShiftDatesEntityTypesItem.java deleted file mode 100644 index a2fb5e64..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/ShiftDatesEntityTypesItem.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum ShiftDatesEntityTypesItem { - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"); - - private final String value; - - ShiftDatesEntityTypesItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenGroupRedactions.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenGroupRedactions.java new file mode 100644 index 00000000..a05b6681 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenGroupRedactions.java @@ -0,0 +1,140 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenGroupRedactions.Builder.class) +public final class TokenGroupRedactions { + private final Optional tokenGroupName; + + private final Optional redaction; + + private final Map additionalProperties; + + private TokenGroupRedactions( + Optional tokenGroupName, Optional redaction, Map additionalProperties) { + this.tokenGroupName = tokenGroupName; + this.redaction = redaction; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the token group to redact. + */ + @JsonProperty("tokenGroupName") + public Optional getTokenGroupName() { + return tokenGroupName; + } + + /** + * @return Name of the redaction to perform. + */ + @JsonProperty("redaction") + public Optional getRedaction() { + return redaction; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenGroupRedactions && equalTo((TokenGroupRedactions) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenGroupRedactions other) { + return tokenGroupName.equals(other.tokenGroupName) && redaction.equals(other.redaction); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tokenGroupName, this.redaction); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional tokenGroupName = Optional.empty(); + + private Optional redaction = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(TokenGroupRedactions other) { + tokenGroupName(other.getTokenGroupName()); + redaction(other.getRedaction()); + return this; + } + + /** + *

                                  Name of the token group to redact.

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

                                  Name of the redaction to perform.

                                  + */ + @JsonSetter(value = "redaction", nulls = Nulls.SKIP) + public Builder redaction(Optional redaction) { + this.redaction = redaction; + return this; + } + + public Builder redaction(String redaction) { + this.redaction = Optional.ofNullable(redaction); + return this; + } + + public TokenGroupRedactions build() { + return new TokenGroupRedactions(tokenGroupName, redaction, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMapping.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMapping.java deleted file mode 100644 index b703895d..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMapping.java +++ /dev/null @@ -1,185 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.*; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = TokenTypeMapping.Builder.class) -public final class TokenTypeMapping { - private final Optional> vaultToken; - - private final Optional> entityOnly; - - private final Optional> entityUnqCounter; - - private final Optional default_; - - private final Map additionalProperties; - - private TokenTypeMapping( - Optional> vaultToken, - Optional> entityOnly, - Optional> entityUnqCounter, - Optional default_, - Map additionalProperties) { - this.vaultToken = vaultToken; - this.entityOnly = entityOnly; - this.entityUnqCounter = entityUnqCounter; - this.default_ = default_; - this.additionalProperties = additionalProperties; - } - - /** - * @return Entity types to replace with vault tokens. - */ - @JsonProperty("vault_token") - public Optional> getVaultToken() { - return vaultToken; - } - - /** - * @return Entity types to replace with entity tokens. - */ - @JsonProperty("entity_only") - public Optional> getEntityOnly() { - return entityOnly; - } - - /** - * @return Entity types to replace with entity tokens with unique counters. - */ - @JsonProperty("entity_unq_counter") - public Optional> getEntityUnqCounter() { - return entityUnqCounter; - } - - /** - * @return Default token type to generate for detected entities. - */ - @JsonProperty("default") - public Optional getDefault() { - return default_; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof TokenTypeMapping && equalTo((TokenTypeMapping) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(TokenTypeMapping other) { - return vaultToken.equals(other.vaultToken) - && entityOnly.equals(other.entityOnly) - && entityUnqCounter.equals(other.entityUnqCounter) - && default_.equals(other.default_); - } - - @Override - public int hashCode() { - return Objects.hash(this.vaultToken, this.entityOnly, this.entityUnqCounter, this.default_); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional> vaultToken = Optional.empty(); - - private Optional> entityOnly = Optional.empty(); - - private Optional> entityUnqCounter = Optional.empty(); - - private Optional default_ = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(TokenTypeMapping other) { - vaultToken(other.getVaultToken()); - entityOnly(other.getEntityOnly()); - entityUnqCounter(other.getEntityUnqCounter()); - default_(other.getDefault()); - return this; - } - - /** - *

                                  Entity types to replace with vault tokens.

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

                                  Entity types to replace with entity tokens.

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

                                  Entity types to replace with entity tokens with unique counters.

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

                                  Default token type to generate for detected entities.

                                  - */ - @JsonSetter(value = "default", nulls = Nulls.SKIP) - public Builder default_(Optional default_) { - this.default_ = default_; - return this; - } - - public Builder default_(TokenTypeMappingDefault default_) { - this.default_ = Optional.ofNullable(default_); - return this; - } - - public TokenTypeMapping build() { - return new TokenTypeMapping(vaultToken, entityOnly, entityUnqCounter, default_, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingDefault.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingDefault.java deleted file mode 100644 index 17893bad..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingDefault.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum TokenTypeMappingDefault { - ENTITY_UNQ_COUNTER("entity_unq_counter"), - - ENTITY_ONLY("entity_only"), - - VAULT_TOKEN("vault_token"); - - private final String value; - - TokenTypeMappingDefault(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingEntityOnlyItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingEntityOnlyItem.java deleted file mode 100644 index c1daa680..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingEntityOnlyItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum TokenTypeMappingEntityOnlyItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - TokenTypeMappingEntityOnlyItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingEntityUnqCounterItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingEntityUnqCounterItem.java deleted file mode 100644 index 6fcf08a9..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingEntityUnqCounterItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum TokenTypeMappingEntityUnqCounterItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - TokenTypeMappingEntityUnqCounterItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingVaultTokenItem.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingVaultTokenItem.java deleted file mode 100644 index 1ffe9a26..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenTypeMappingVaultTokenItem.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum TokenTypeMappingVaultTokenItem { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER("gender"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"), - - SEXUALITY("sexuality"), - - EFFECT("effect"), - - PROJECT("project"), - - ORGANIZATION_ID("organization_id"), - - DAY("day"), - - MONTH("month"), - - YEAR("year"); - - private final String value; - - TokenTypeMappingVaultTokenItem(String value) { - this.value = value; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRecordRequest.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRecordRequest.java new file mode 100644 index 00000000..764f5af5 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRecordRequest.java @@ -0,0 +1,203 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenizeRecordRequest.Builder.class) +public final class TokenizeRecordRequest { + private final Optional value; + + private final Optional table; + + private final Optional column; + + private final Optional columnGroup; + + private final Map additionalProperties; + + private TokenizeRecordRequest( + Optional value, + Optional table, + Optional column, + Optional columnGroup, + Map additionalProperties) { + this.value = value; + this.table = table; + this.column = column; + this.columnGroup = columnGroup; + this.additionalProperties = additionalProperties; + } + + /** + * @return Existing value to return a token for. Must be specified with either columnGroup or both table and column. + */ + @JsonProperty("value") + public Optional getValue() { + return value; + } + + /** + * @return Name of the table that the value belongs to. Must be specified with column. Can't be specified with columnGroup. + */ + @JsonProperty("table") + public Optional getTable() { + return table; + } + + /** + * @return Name of the column that the value belongs to. Must be specified with table. Can't be specified with columnGroup. + */ + @JsonProperty("column") + public Optional getColumn() { + return column; + } + + /** + * @return Name of the column group that the value belongs to. Can't be specified with table or column. + */ + @JsonProperty("columnGroup") + public Optional getColumnGroup() { + return columnGroup; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenizeRecordRequest && equalTo((TokenizeRecordRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenizeRecordRequest other) { + return value.equals(other.value) + && table.equals(other.table) + && column.equals(other.column) + && columnGroup.equals(other.columnGroup); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value, this.table, this.column, this.columnGroup); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional value = Optional.empty(); + + private Optional table = Optional.empty(); + + private Optional column = Optional.empty(); + + private Optional columnGroup = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(TokenizeRecordRequest other) { + value(other.getValue()); + table(other.getTable()); + column(other.getColumn()); + columnGroup(other.getColumnGroup()); + return this; + } + + /** + *

                                  Existing value to return a token for. Must be specified with either columnGroup or both table and column.

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

                                  Name of the table that the value belongs to. Must be specified with column. Can't be specified with columnGroup.

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

                                  Name of the column that the value belongs to. Must be specified with table. Can't be specified with columnGroup.

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

                                  Name of the column group that the value belongs to. Can't be specified with table or column.

                                  + */ + @JsonSetter(value = "columnGroup", nulls = Nulls.SKIP) + public Builder columnGroup(Optional columnGroup) { + this.columnGroup = columnGroup; + return this; + } + + public Builder columnGroup(String columnGroup) { + this.columnGroup = Optional.ofNullable(columnGroup); + return this; + } + + public TokenizeRecordRequest build() { + return new TokenizeRecordRequest(value, table, column, columnGroup, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRecordResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRecordResponse.java new file mode 100644 index 00000000..9de12f17 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRecordResponse.java @@ -0,0 +1,128 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenizeRecordResponse.Builder.class) +public final class TokenizeRecordResponse { + private final String token; + + private final Map additionalProperties; + + private TokenizeRecordResponse(String token, Map additionalProperties) { + this.token = token; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token corresponding to a value. + */ + @JsonProperty("token") + public String getToken() { + return token; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenizeRecordResponse && equalTo((TokenizeRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenizeRecordResponse other) { + return token.equals(other.token); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TokenStage builder() { + return new Builder(); + } + + public interface TokenStage { + /** + *

                                  Token corresponding to a value.

                                  + */ + _FinalStage token(@NotNull String token); + + Builder from(TokenizeRecordResponse other); + } + + public interface _FinalStage { + TokenizeRecordResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TokenStage, _FinalStage { + private String token; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(TokenizeRecordResponse other) { + token(other.getToken()); + return this; + } + + /** + *

                                  Token corresponding to a value.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("token") + public _FinalStage token(@NotNull String token) { + this.token = Objects.requireNonNull(token, "token must not be null"); + return this; + } + + @java.lang.Override + public TokenizeRecordResponse build() { + return new TokenizeRecordResponse(token, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRequestObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRequestObject.java new file mode 100644 index 00000000..6cffce95 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeRequestObject.java @@ -0,0 +1,212 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenizeRequestObject.Builder.class) +public final class TokenizeRequestObject { + private final GoogleProtobufValue value; + + private final List tokenGroupNames; + + private final Optional token; + + private final Map additionalProperties; + + private TokenizeRequestObject( + GoogleProtobufValue value, + List tokenGroupNames, + Optional token, + Map additionalProperties) { + this.value = value; + this.tokenGroupNames = tokenGroupNames; + this.token = token; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("value") + public GoogleProtobufValue getValue() { + return value; + } + + /** + * @return Names of token groups the value might be present in. + */ + @JsonProperty("tokenGroupNames") + public List getTokenGroupNames() { + return tokenGroupNames; + } + + @JsonProperty("token") + public Optional getToken() { + return token; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenizeRequestObject && equalTo((TokenizeRequestObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenizeRequestObject other) { + return value.equals(other.value) && tokenGroupNames.equals(other.tokenGroupNames) && token.equals(other.token); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value, this.tokenGroupNames, this.token); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ValueStage builder() { + return new Builder(); + } + + public interface ValueStage { + _FinalStage value(@NotNull GoogleProtobufValue value); + + Builder from(TokenizeRequestObject other); + } + + public interface _FinalStage { + TokenizeRequestObject build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Names of token groups the value might be present in.

                                  + */ + _FinalStage tokenGroupNames(List tokenGroupNames); + + _FinalStage addTokenGroupNames(String tokenGroupNames); + + _FinalStage addAllTokenGroupNames(List tokenGroupNames); + + _FinalStage token(Optional token); + + _FinalStage token(GoogleProtobufValue token); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ValueStage, _FinalStage { + private GoogleProtobufValue value; + + private Optional token = Optional.empty(); + + private List tokenGroupNames = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(TokenizeRequestObject other) { + value(other.getValue()); + tokenGroupNames(other.getTokenGroupNames()); + token(other.getToken()); + return this; + } + + @java.lang.Override + @JsonSetter("value") + public _FinalStage value(@NotNull GoogleProtobufValue value) { + this.value = Objects.requireNonNull(value, "value must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage token(GoogleProtobufValue token) { + this.token = Optional.ofNullable(token); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token", nulls = Nulls.SKIP) + public _FinalStage token(Optional token) { + this.token = token; + return this; + } + + /** + *

                                  Names of token groups the value might be present in.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllTokenGroupNames(List tokenGroupNames) { + if (tokenGroupNames != null) { + this.tokenGroupNames.addAll(tokenGroupNames); + } + return this; + } + + /** + *

                                  Names of token groups the value might be present in.

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

                                  Names of token groups the value might be present in.

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

                                  Tokens corresponding to the specified values.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(TokenizeRecordResponse records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public TokenizeResponse build() { + return new TokenizeResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeResponseObject.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeResponseObject.java new file mode 100644 index 00000000..70f9d9dc --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/TokenizeResponseObject.java @@ -0,0 +1,321 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.Nullable; +import com.skyflow.generated.rest.core.NullableNonemptyFilter; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenizeResponseObject.Builder.class) +public final class TokenizeResponseObject { + private final String token; + + private final Optional value; + + private final Optional tokenGroupName; + + private final Optional error; + + private final Optional httpCode; + + private final Map additionalProperties; + + private TokenizeResponseObject( + String token, + Optional value, + Optional tokenGroupName, + Optional error, + Optional httpCode, + Map additionalProperties) { + this.token = token; + this.value = value; + this.tokenGroupName = tokenGroupName; + this.error = error; + this.httpCode = httpCode; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token that was generated. + */ + @JsonProperty("token") + public String getToken() { + return token; + } + + @JsonProperty("value") + public Optional getValue() { + return value; + } + + /** + * @return Name of the token group. + */ + @JsonIgnore + public Optional getTokenGroupName() { + if (tokenGroupName == null) { + return Optional.empty(); + } + return tokenGroupName; + } + + /** + * @return Error message, if any. + */ + @JsonProperty("error") + public Optional getError() { + return error; + } + + /** + * @return HTTP status code of the response. + */ + @JsonProperty("httpCode") + public Optional getHttpCode() { + return httpCode; + } + + @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = NullableNonemptyFilter.class) + @JsonProperty("tokenGroupName") + private Optional _getTokenGroupName() { + return tokenGroupName; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenizeResponseObject && equalTo((TokenizeResponseObject) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenizeResponseObject other) { + return token.equals(other.token) + && value.equals(other.value) + && tokenGroupName.equals(other.tokenGroupName) + && error.equals(other.error) + && httpCode.equals(other.httpCode); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token, this.value, this.tokenGroupName, this.error, this.httpCode); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TokenStage builder() { + return new Builder(); + } + + public interface TokenStage { + /** + *

                                  Token that was generated.

                                  + */ + _FinalStage token(@NotNull String token); + + Builder from(TokenizeResponseObject other); + } + + public interface _FinalStage { + TokenizeResponseObject build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + _FinalStage value(Optional value); + + _FinalStage value(GoogleProtobufValue value); + + /** + *

                                  Name of the token group.

                                  + */ + _FinalStage tokenGroupName(Optional tokenGroupName); + + _FinalStage tokenGroupName(String tokenGroupName); + + _FinalStage tokenGroupName(Nullable tokenGroupName); + + /** + *

                                  Error message, if any.

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

                                  HTTP status code of the response.

                                  + */ + _FinalStage httpCode(Optional httpCode); + + _FinalStage httpCode(Integer httpCode); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TokenStage, _FinalStage { + private String token; + + private Optional httpCode = Optional.empty(); + + private Optional error = Optional.empty(); + + private Optional tokenGroupName = Optional.empty(); + + private Optional value = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(TokenizeResponseObject other) { + token(other.getToken()); + value(other.getValue()); + tokenGroupName(other.getTokenGroupName()); + error(other.getError()); + httpCode(other.getHttpCode()); + return this; + } + + /** + *

                                  Token that was generated.

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

                                  HTTP status code of the response.

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

                                  HTTP status code of the response.

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

                                  Error message, if any.

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

                                  Error message, if any.

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

                                  Name of the token group.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage tokenGroupName(Nullable tokenGroupName) { + if (tokenGroupName.isNull()) { + this.tokenGroupName = null; + } else if (tokenGroupName.isEmpty()) { + this.tokenGroupName = Optional.empty(); + } else { + this.tokenGroupName = Optional.of(tokenGroupName.get()); + } + return this; + } + + /** + *

                                  Name of the token group.

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

                                  Name of the token group.

                                  + */ + @java.lang.Override + @JsonSetter(value = "tokenGroupName", nulls = Nulls.SKIP) + public _FinalStage tokenGroupName(Optional tokenGroupName) { + this.tokenGroupName = tokenGroupName; + return this; + } + + @java.lang.Override + public _FinalStage value(GoogleProtobufValue value) { + this.value = Optional.ofNullable(value); + return this; + } + + @java.lang.Override + @JsonSetter(value = "value", nulls = Nulls.SKIP) + public _FinalStage value(Optional value) { + this.value = value; + return this; + } + + @java.lang.Override + public TokenizeResponseObject build() { + return new TokenizeResponseObject(token, value, tokenGroupName, error, httpCode, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/Transformations.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/Transformations.java deleted file mode 100644 index c9165409..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/Transformations.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = Transformations.Builder.class) -public final class Transformations { - private final Optional shiftDates; - - private final Map additionalProperties; - - private Transformations(Optional shiftDates, Map additionalProperties) { - this.shiftDates = shiftDates; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("shift_dates") - public Optional getShiftDates() { - return shiftDates; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof Transformations && equalTo((Transformations) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(Transformations other) { - return shiftDates.equals(other.shiftDates); - } - - @Override - public int hashCode() { - return Objects.hash(this.shiftDates); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional shiftDates = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(Transformations other) { - shiftDates(other.getShiftDates()); - return this; - } - - @JsonSetter(value = "shift_dates", nulls = Nulls.SKIP) - public Builder shiftDates(Optional shiftDates) { - this.shiftDates = shiftDates; - return this; - } - - public Builder shiftDates(ShiftDates shiftDates) { - this.shiftDates = Optional.ofNullable(shiftDates); - return this; - } - - public Transformations build() { - return new Transformations(shiftDates, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/UniqueValue.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/UniqueValue.java new file mode 100644 index 00000000..7c185437 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/UniqueValue.java @@ -0,0 +1,121 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = UniqueValue.Builder.class) +public final class UniqueValue { + private final Map data; + + private final Map additionalProperties; + + private UniqueValue(Map data, Map additionalProperties) { + this.data = data; + this.additionalProperties = additionalProperties; + } + + /** + * @return Columns names and values for the unique value entry. + */ + @JsonProperty("data") + public Map getData() { + return data; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof UniqueValue && equalTo((UniqueValue) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(UniqueValue other) { + return data.equals(other.data); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.data); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Map data = new LinkedHashMap<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(UniqueValue other) { + data(other.getData()); + return this; + } + + /** + *

                                  Columns names and values for the unique value entry.

                                  + */ + @JsonSetter(value = "data", nulls = Nulls.SKIP) + public Builder data(Map data) { + this.data.clear(); + if (data != null) { + this.data.putAll(data); + } + return this; + } + + public Builder putAllData(Map data) { + if (data != null) { + this.data.putAll(data); + } + return this; + } + + public Builder data(String key, Object value) { + this.data.put(key, value); + return this; + } + + public UniqueValue build() { + return new UniqueValue(data, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordData.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordData.java new file mode 100644 index 00000000..83a11ab0 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordData.java @@ -0,0 +1,279 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = UpdateRecordData.Builder.class) +public final class UpdateRecordData { + private final String skyflowId; + + private final Map data; + + private final Optional tableName; + + private final Optional updateType; + + private final Map additionalProperties; + + private UpdateRecordData( + String skyflowId, + Map data, + Optional tableName, + Optional updateType, + Map additionalProperties) { + this.skyflowId = skyflowId; + this.data = data; + this.tableName = tableName; + this.updateType = updateType; + this.additionalProperties = additionalProperties; + } + + /** + * @return Skyflow ID of the record to update. + */ + @JsonProperty("skyflowID") + public String getSkyflowId() { + return skyflowId; + } + + /** + * @return Columns and values for the record. + */ + @JsonProperty("data") + public Map getData() { + return data; + } + + /** + * @return Name of the table to update data in. + */ + @JsonProperty("tableName") + public Optional getTableName() { + return tableName; + } + + /** + * @return Type of update operation to perform. + */ + @JsonProperty("updateType") + public Optional getUpdateType() { + return updateType; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof UpdateRecordData && equalTo((UpdateRecordData) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(UpdateRecordData other) { + return skyflowId.equals(other.skyflowId) + && data.equals(other.data) + && tableName.equals(other.tableName) + && updateType.equals(other.updateType); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.data, this.tableName, this.updateType); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static SkyflowIdStage builder() { + return new Builder(); + } + + public interface SkyflowIdStage { + /** + *

                                  Skyflow ID of the record to update.

                                  + */ + _FinalStage skyflowId(@NotNull String skyflowId); + + Builder from(UpdateRecordData other); + } + + public interface _FinalStage { + UpdateRecordData build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

                                  Columns and values for the record.

                                  + */ + _FinalStage data(Map data); + + _FinalStage putAllData(Map data); + + _FinalStage data(String key, Object value); + + /** + *

                                  Name of the table to update data in.

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

                                  Type of update operation to perform.

                                  + */ + _FinalStage updateType(Optional updateType); + + _FinalStage updateType(UpdateRecordDataUpdateType updateType); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements SkyflowIdStage, _FinalStage { + private String skyflowId; + + private Optional updateType = Optional.empty(); + + private Optional tableName = Optional.empty(); + + private Map data = new LinkedHashMap<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(UpdateRecordData other) { + skyflowId(other.getSkyflowId()); + data(other.getData()); + tableName(other.getTableName()); + updateType(other.getUpdateType()); + return this; + } + + /** + *

                                  Skyflow ID of the record to update.

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

                                  Type of update operation to perform.

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

                                  Type of update operation to perform.

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

                                  Name of the table to update data in.

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

                                  Name of the table to update data in.

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

                                  Columns and values for the record.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage data(String key, Object value) { + this.data.put(key, value); + return this; + } + + /** + *

                                  Columns and values for the record.

                                  + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage putAllData(Map data) { + if (data != null) { + this.data.putAll(data); + } + return this; + } + + /** + *

                                  Columns and values for the record.

                                  + */ + @java.lang.Override + @JsonSetter(value = "data", nulls = Nulls.SKIP) + public _FinalStage data(Map data) { + this.data.clear(); + if (data != null) { + this.data.putAll(data); + } + return this; + } + + @java.lang.Override + public UpdateRecordData build() { + return new UpdateRecordData(skyflowId, data, tableName, updateType, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordDataUpdateType.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordDataUpdateType.java new file mode 100644 index 00000000..2fe52e9d --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordDataUpdateType.java @@ -0,0 +1,84 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class UpdateRecordDataUpdateType { + public static final UpdateRecordDataUpdateType REPLACE = new UpdateRecordDataUpdateType(Value.REPLACE, "REPLACE"); + + public static final UpdateRecordDataUpdateType UPDATE = new UpdateRecordDataUpdateType(Value.UPDATE, "UPDATE"); + + private final Value value; + + private final String string; + + UpdateRecordDataUpdateType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof UpdateRecordDataUpdateType + && this.string.equals(((UpdateRecordDataUpdateType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case REPLACE: + return visitor.visitReplace(); + case UPDATE: + return visitor.visitUpdate(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static UpdateRecordDataUpdateType valueOf(String value) { + switch (value) { + case "REPLACE": + return REPLACE; + case "UPDATE": + return UPDATE; + default: + return new UpdateRecordDataUpdateType(Value.UNKNOWN, value); + } + } + + public enum Value { + UPDATE, + + REPLACE, + + UNKNOWN + } + + public interface Visitor { + T visitUpdate(); + + T visitReplace(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1UpdateRecordResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordResponse.java similarity index 70% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/V1UpdateRecordResponse.java rename to skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordResponse.java index d2fcbf1b..a4b4fd87 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1UpdateRecordResponse.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateRecordResponse.java @@ -3,25 +3,30 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; - import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1UpdateRecordResponse.Builder.class) -public final class V1UpdateRecordResponse { +@JsonDeserialize(builder = UpdateRecordResponse.Builder.class) +public final class UpdateRecordResponse { private final Optional skyflowId; private final Optional> tokens; private final Map additionalProperties; - private V1UpdateRecordResponse( + private UpdateRecordResponse( Optional skyflowId, Optional> tokens, Map additionalProperties) { @@ -46,10 +51,10 @@ public Optional> getTokens() { return tokens; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof V1UpdateRecordResponse && equalTo((V1UpdateRecordResponse) other); + return other instanceof UpdateRecordResponse && equalTo((UpdateRecordResponse) other); } @JsonAnyGetter @@ -57,16 +62,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(V1UpdateRecordResponse other) { + private boolean equalTo(UpdateRecordResponse other) { return skyflowId.equals(other.skyflowId) && tokens.equals(other.tokens); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.skyflowId, this.tokens); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -86,7 +91,7 @@ public static final class Builder { private Builder() {} - public Builder from(V1UpdateRecordResponse other) { + public Builder from(UpdateRecordResponse other) { skyflowId(other.getSkyflowId()); tokens(other.getTokens()); return this; @@ -120,8 +125,18 @@ public Builder tokens(Map tokens) { return this; } - public V1UpdateRecordResponse build() { - return new V1UpdateRecordResponse(skyflowId, tokens, additionalProperties); + public UpdateRecordResponse build() { + return new UpdateRecordResponse(skyflowId, tokens, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateResponse.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateResponse.java new file mode 100644 index 00000000..7f509065 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpdateResponse.java @@ -0,0 +1,122 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = UpdateResponse.Builder.class) +public final class UpdateResponse { + private final List records; + + private final Map additionalProperties; + + private UpdateResponse(List records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return List of updated records. + */ + @JsonProperty("records") + public List getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof UpdateResponse && equalTo((UpdateResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(UpdateResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private List records = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(UpdateResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

                                  List of updated records.

                                  + */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(List records) { + this.records.clear(); + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public Builder addRecords(RecordResponseObject records) { + this.records.add(records); + return this; + } + + public Builder addAllRecords(List records) { + if (records != null) { + this.records.addAll(records); + } + return this; + } + + public UpdateResponse build() { + return new UpdateResponse(records, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/UploadFileResponseV2.java similarity index 53% rename from skyvault/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java rename to skyvault/src/main/java/com/skyflow/generated/rest/types/UploadFileResponseV2.java index 8f5fea5a..b4d0ca27 100644 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/UploadFileResponseV2.java @@ -3,48 +3,58 @@ */ package com.skyflow.generated.rest.types; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; - import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = UploadFileV2Response.Builder.class) -public final class UploadFileV2Response { +@JsonDeserialize(builder = UploadFileResponseV2.Builder.class) +public final class UploadFileResponseV2 { private final Optional skyflowId; - private final Optional fileMetadata; + private final Optional> fileMetadata; private final Map additionalProperties; - private UploadFileV2Response( - Optional skyflowId, Optional fileMetadata, Map additionalProperties) { + private UploadFileResponseV2( + Optional skyflowId, + Optional> fileMetadata, + Map additionalProperties) { this.skyflowId = skyflowId; this.fileMetadata = fileMetadata; this.additionalProperties = additionalProperties; } /** - * @return Skyflow ID of the record the file was uploaded to. + * @return ID of the record to update. */ @JsonProperty("skyflowID") public Optional getSkyflowId() { return skyflowId; } + /** + * @return Metadata for the uploaded file with keys based on the name of the column containing the file. + */ @JsonProperty("fileMetadata") - public Optional getFileMetadata() { + public Optional> getFileMetadata() { return fileMetadata; } - @Override + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof UploadFileV2Response && equalTo((UploadFileV2Response) other); + return other instanceof UploadFileResponseV2 && equalTo((UploadFileResponseV2) other); } @JsonAnyGetter @@ -52,16 +62,16 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(UploadFileV2Response other) { + private boolean equalTo(UploadFileResponseV2 other) { return skyflowId.equals(other.skyflowId) && fileMetadata.equals(other.fileMetadata); } - @Override + @java.lang.Override public int hashCode() { return Objects.hash(this.skyflowId, this.fileMetadata); } - @Override + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); } @@ -74,21 +84,21 @@ public static Builder builder() { public static final class Builder { private Optional skyflowId = Optional.empty(); - private Optional fileMetadata = Optional.empty(); + private Optional> fileMetadata = Optional.empty(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} - public Builder from(UploadFileV2Response other) { + public Builder from(UploadFileResponseV2 other) { skyflowId(other.getSkyflowId()); fileMetadata(other.getFileMetadata()); return this; } /** - *

                                  Skyflow ID of the record the file was uploaded to.

                                  + *

                                  ID of the record to update.

                                  */ @JsonSetter(value = "skyflowID", nulls = Nulls.SKIP) public Builder skyflowId(Optional skyflowId) { @@ -101,19 +111,32 @@ public Builder skyflowId(String skyflowId) { return this; } + /** + *

                                  Metadata for the uploaded file with keys based on the name of the column containing the file.

                                  + */ @JsonSetter(value = "fileMetadata", nulls = Nulls.SKIP) - public Builder fileMetadata(Optional fileMetadata) { + public Builder fileMetadata(Optional> fileMetadata) { this.fileMetadata = fileMetadata; return this; } - public Builder fileMetadata(Object fileMetadata) { + public Builder fileMetadata(Map fileMetadata) { this.fileMetadata = Optional.ofNullable(fileMetadata); return this; } - public UploadFileV2Response build() { - return new UploadFileV2Response(skyflowId, fileMetadata, additionalProperties); + public UploadFileResponseV2 build() { + return new UploadFileResponseV2(skyflowId, fileMetadata, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/Upsert.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/Upsert.java new file mode 100644 index 00000000..d413f637 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/Upsert.java @@ -0,0 +1,154 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = Upsert.Builder.class) +public final class Upsert { + private final Optional updateType; + + private final List uniqueColumns; + + private final Map additionalProperties; + + private Upsert( + Optional updateType, + List uniqueColumns, + Map additionalProperties) { + this.updateType = updateType; + this.uniqueColumns = uniqueColumns; + this.additionalProperties = additionalProperties; + } + + /** + * @return Type of update operation to perform. + */ + @JsonProperty("updateType") + public Optional getUpdateType() { + return updateType; + } + + /** + * @return List of unique columns in the table that upsert operations use to identify if a record with matching values exists. If a matching record exists, the record updates with the specified values. If a matching record doesn't exist, the upsert operation inserts a new record. + */ + @JsonProperty("uniqueColumns") + public List getUniqueColumns() { + return uniqueColumns; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof Upsert && equalTo((Upsert) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(Upsert other) { + return updateType.equals(other.updateType) && uniqueColumns.equals(other.uniqueColumns); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.updateType, this.uniqueColumns); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional updateType = Optional.empty(); + + private List uniqueColumns = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(Upsert other) { + updateType(other.getUpdateType()); + uniqueColumns(other.getUniqueColumns()); + return this; + } + + /** + *

                                  Type of update operation to perform.

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

                                  List of unique columns in the table that upsert operations use to identify if a record with matching values exists. If a matching record exists, the record updates with the specified values. If a matching record doesn't exist, the upsert operation inserts a new record.

                                  + */ + @JsonSetter(value = "uniqueColumns", nulls = Nulls.SKIP) + public Builder uniqueColumns(List uniqueColumns) { + this.uniqueColumns.clear(); + if (uniqueColumns != null) { + this.uniqueColumns.addAll(uniqueColumns); + } + return this; + } + + public Builder addUniqueColumns(String uniqueColumns) { + this.uniqueColumns.add(uniqueColumns); + return this; + } + + public Builder addAllUniqueColumns(List uniqueColumns) { + if (uniqueColumns != null) { + this.uniqueColumns.addAll(uniqueColumns); + } + return this; + } + + public Upsert build() { + return new Upsert(updateType, uniqueColumns, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/UpsertUpdateType.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpsertUpdateType.java new file mode 100644 index 00000000..09196134 --- /dev/null +++ b/skyvault/src/main/java/com/skyflow/generated/rest/types/UpsertUpdateType.java @@ -0,0 +1,83 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class UpsertUpdateType { + public static final UpsertUpdateType REPLACE = new UpsertUpdateType(Value.REPLACE, "REPLACE"); + + public static final UpsertUpdateType UPDATE = new UpsertUpdateType(Value.UPDATE, "UPDATE"); + + private final Value value; + + private final String string; + + UpsertUpdateType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof UpsertUpdateType && this.string.equals(((UpsertUpdateType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case REPLACE: + return visitor.visitReplace(); + case UPDATE: + return visitor.visitUpdate(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static UpsertUpdateType valueOf(String value) { + switch (value) { + case "REPLACE": + return REPLACE; + case "UPDATE": + return UPDATE; + default: + return new UpsertUpdateType(Value.UNKNOWN, value); + } + } + + public enum Value { + UPDATE, + + REPLACE, + + UNKNOWN + } + + public interface Visitor { + T visitUpdate(); + + T visitReplace(); + + T visitUnknown(String unknownType); + } +} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1AuditAfterOptions.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/V1AuditAfterOptions.java deleted file mode 100644 index 037b80bf..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/V1AuditAfterOptions.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1AuditAfterOptions.Builder.class) -public final class V1AuditAfterOptions { - private final Optional timestamp; - - private final Optional changeId; - - private final Map additionalProperties; - - private V1AuditAfterOptions( - Optional timestamp, Optional changeId, Map additionalProperties) { - this.timestamp = timestamp; - this.changeId = changeId; - this.additionalProperties = additionalProperties; - } - - /** - * @return Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. - */ - @JsonProperty("timestamp") - public Optional getTimestamp() { - return timestamp; - } - - /** - * @return Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. - */ - @JsonProperty("changeID") - public Optional getChangeId() { - return changeId; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1AuditAfterOptions && equalTo((V1AuditAfterOptions) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1AuditAfterOptions other) { - return timestamp.equals(other.timestamp) && changeId.equals(other.changeId); - } - - @Override - public int hashCode() { - return Objects.hash(this.timestamp, this.changeId); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional timestamp = Optional.empty(); - - private Optional changeId = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1AuditAfterOptions other) { - timestamp(other.getTimestamp()); - changeId(other.getChangeId()); - return this; - } - - /** - *

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

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

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

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

                                  The status of the overall operation.

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

                                  The status message for the overall operation.

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

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

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

                                  Events matching the query.

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

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

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

                                  ID of the account that made the request.

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

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

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

                                  API name.

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

                                  The workspaceID (if any) of the request.

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

                                  The vaultID (if any) of the request.

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

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

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

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

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

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

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

                                  Name of the table to perform the operation on.

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

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

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

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

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

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

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

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

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

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

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

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

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

                                  Card metadata associated with the specified BIN.

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

                                  The specified records.

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

                                  BIN of the card.

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

                                  Name of the card issuer bank.

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

                                  Country code of the card.

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

                                  Currency of the card.

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

                                  Type of the card.

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

                                  Category of the card.

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

                                  Scheme of the card.

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

                                  Last four digits of the card number.

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

                                  Expiry date of the card.

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

                                  ID of the record.

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

                                  If true, the file was deleted.

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

                                  Token that identifies the record to detokenize.

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

                                  Records corresponding to the specified tokens.

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

                                  AccessToken.

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

                                  TokenType : Bearer.

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

                                  Records returned by the query.

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

                                  Identifiers for the inserted records.

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

                                  Existing value to return a token for.

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

                                  Name of the column group that the value belongs to.

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

                                  Token corresponding to a value.

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

                                  Tokens corresponding to the specified values.

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

                                  Name of the column that stores the card number.

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

                                  Name of the column that stores the card number suffix.

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

                                  Name of the column that stores the expiry date.

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

                                  ID of the vault that stores card details.

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

                                  Name of the table that stores card details.

                                  - */ - @JsonSetter(value = "table_name", nulls = Nulls.SKIP) - public Builder tableName(Optional tableName) { - this.tableName = tableName; - return this; - } - - public Builder tableName(String tableName) { - this.tableName = Optional.ofNullable(tableName); - return this; - } - - @JsonSetter(value = "mapping", nulls = Nulls.SKIP) - public Builder mapping(Optional mapping) { - this.mapping = mapping; - return this; - } - - public Builder mapping(V1VaultFieldMapping mapping) { - this.mapping = Optional.ofNullable(mapping); - return this; - } - - public V1VaultSchemaConfig build() { - return new V1VaultSchemaConfig(id, tableName, mapping, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/generated/rest/types/WordCharacterCount.java b/skyvault/src/main/java/com/skyflow/generated/rest/types/WordCharacterCount.java deleted file mode 100644 index 314b5942..00000000 --- a/skyvault/src/main/java/com/skyflow/generated/rest/types/WordCharacterCount.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = WordCharacterCount.Builder.class) -public final class WordCharacterCount { - private final Optional wordCount; - - private final Optional characterCount; - - private final Map additionalProperties; - - private WordCharacterCount( - Optional wordCount, Optional characterCount, Map additionalProperties) { - this.wordCount = wordCount; - this.characterCount = characterCount; - this.additionalProperties = additionalProperties; - } - - /** - * @return Number of words in the processed text. - */ - @JsonProperty("wordCount") - public Optional getWordCount() { - return wordCount; - } - - /** - * @return Number of characters in the processed text. - */ - @JsonProperty("characterCount") - public Optional getCharacterCount() { - return characterCount; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof WordCharacterCount && equalTo((WordCharacterCount) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(WordCharacterCount other) { - return wordCount.equals(other.wordCount) && characterCount.equals(other.characterCount); - } - - @Override - public int hashCode() { - return Objects.hash(this.wordCount, this.characterCount); - } - - @Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional wordCount = Optional.empty(); - - private Optional characterCount = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(WordCharacterCount other) { - wordCount(other.getWordCount()); - characterCount(other.getCharacterCount()); - return this; - } - - /** - *

                                  Number of words in the processed text.

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

                                  Number of characters in the processed text.

                                  - */ - @JsonSetter(value = "characterCount", nulls = Nulls.SKIP) - public Builder characterCount(Optional characterCount) { - this.characterCount = characterCount; - return this; - } - - public Builder characterCount(Integer characterCount) { - this.characterCount = Optional.ofNullable(characterCount); - return this; - } - - public WordCharacterCount build() { - return new WordCharacterCount(wordCount, characterCount, additionalProperties); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/utils/Constants.java b/skyvault/src/main/java/com/skyflow/utils/Constants.java index 0c65a72b..82f6dd04 100644 --- a/skyvault/src/main/java/com/skyflow/utils/Constants.java +++ b/skyvault/src/main/java/com/skyflow/utils/Constants.java @@ -10,8 +10,6 @@ public final class Constants extends BaseConstants { public static final String SDK_VERSION; public static final String SDK_PREFIX; public static final String SDK_METRIC_NAME_VERSION_PREFIX = "skyflow-java@"; - public static final String PROCESSED_FILE_NAME_PREFIX = "processed-"; - public static final String DEIDENTIFIED_FILE_PREFIX = "deidentified"; public static final String HTTPS_PROTOCOL = "https"; public static final String ORDER_DESCENDING = "DESCENDING"; public static final String ORDER_NONE = "NONE"; diff --git a/skyvault/src/main/java/com/skyflow/utils/validations/Validations.java b/skyvault/src/main/java/com/skyflow/utils/validations/Validations.java index 93957f57..48b9b34d 100644 --- a/skyvault/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/skyvault/src/main/java/com/skyflow/utils/validations/Validations.java @@ -30,11 +30,6 @@ import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.QueryRequest; import com.skyflow.vault.data.UpdateRequest; -import com.skyflow.vault.detect.DeidentifyFileRequest; -import com.skyflow.vault.detect.DeidentifyTextRequest; -import com.skyflow.vault.detect.GetDetectRunRequest; -import com.skyflow.vault.detect.ReidentifyTextRequest; -import com.skyflow.vault.detect.TokenFormat; import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; @@ -754,40 +749,6 @@ private static boolean isNullOrEmpty(String str) { return str == null || str.trim().isEmpty(); } - public static void validateDeidentifyTextRequest(DeidentifyTextRequest deidentifyTextRequest) throws SkyflowException { - if (deidentifyTextRequest == null) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.DEIDENTIFY_TEXT_REQUEST_NULL.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.DeidentifyTextRequestNull.getMessage()); - } - // Validate required fields - String deidentifyText = deidentifyTextRequest.getText(); - if (deidentifyText == null || deidentifyText.trim().isEmpty()) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INVALID_TEXT_IN_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTextInDeIdentify.getMessage()); - } - } - - public static void validateReidentifyTextRequest(ReidentifyTextRequest reidentifyTextRequest) throws SkyflowException { - if (reidentifyTextRequest == null) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.REIDENTIFY_TEXT_REQUEST_NULL.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ReidentifyTextRequestNull.getMessage()); - } - // Validate required fields - String reidentifyText = reidentifyTextRequest.getText(); - if (reidentifyText == null || reidentifyText.trim().isEmpty()) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INVALID_TEXT_IN_REIDENTIFY.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTextInReIdentify.getMessage()); - } - } - private static boolean isInvalidURL(String configURL) { try { URL url = new URL(configURL); @@ -863,129 +824,10 @@ private static void validateTokensMapWithTokenStrict( } } - public static void validateDeidentifyFileRequest(DeidentifyFileRequest request) throws SkyflowException { - if (request == null) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_REQUEST_BODY.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); - } - - TokenFormat tokenFormat = request.getTokenFormat(); - if (tokenFormat != null && tokenFormat.getVaultToken() != null && !tokenFormat.getVaultToken().isEmpty()) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultTokenFormatIsNotAllowedForFiles.getMessage()); - } - - if (request.getFileInput() == null) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_FILE_AND_FILE_PATH_IN_DEIDENTIFY_FILE.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage()); - } - - File file = request.getFileInput().getFile(); - String filePath = request.getFileInput().getFilePath(); - - if (file == null && filePath == null) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_FILE_AND_FILE_PATH_IN_DEIDENTIFY_FILE.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage()); - } - - if (filePath != null && file != null) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.BothFileAndFilePathProvided.getMessage()); - } - - if (filePath != null && filePath.trim().isEmpty()){ - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidFilePath.getMessage()); - } - - if (file != null && (!file.exists() || !file.isFile())) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.FILE_NOT_FOUND_TO_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FileNotFoundToDeidentify.getMessage()); - } - if (file != null && !file.canRead()) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.FILE_NOT_READABLE_TO_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FileNotReadableToDeidentify.getMessage()); - } - - - // Validate pixelDensity and maxResolution - if (request.getPixelDensity() != null && request.getPixelDensity().doubleValue() <= 0) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INVALID_PIXEL_DENSITY_TO_DEIDENTIFY_FILE.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidPixelDensityToDeidentifyFile.getMessage()); - } - if (request.getMaxResolution() != null && request.getMaxResolution().doubleValue() <= 0) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INVALID_MAX_RESOLUTION.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidMaxResolution.getMessage()); - } - - // Validate AudioBleep - if (request.getBleep() != null) { - if (request.getBleep().getFrequency() == null || request.getBleep().getFrequency() <= 0) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INVALID_BLEEP_TO_DEIDENTIFY_AUDIO.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); - } - if (request.getBleep().getStartPadding() == null || request.getBleep().getStartPadding() < 0) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); - } - if (request.getBleep().getStopPadding() == null || request.getBleep().getStopPadding() < 0) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); - } - } - - // Validate outputDirectory if provided - if (request.getOutputDirectory() != null) { - File outDir = new File(request.getOutputDirectory()); - if (!outDir.exists() || !outDir.isDirectory()) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.OUTPUT_DIRECTORY_NOT_FOUND.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.OutputDirectoryNotFound.getMessage()); - } - if (!outDir.canWrite()) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INVALID_PERMISSIONS_FOR_OUTPUT_DIRECTORY.getLog(), InterfaceName.DETECT.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidPermission.getMessage()); - } - } - - // Validate waitTime if provided - if (request.getWaitTime() != null && request.getWaitTime() <= 0) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidWaitTime.getMessage()); - } - if(request.getWaitTime() != null && request.getWaitTime() > 64) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.WaitTimeExceedsLimit.getMessage()); - } - } - static Object resolveUpdateId(HashMap data) { if (data.containsKey("skyflowId")) { return data.get("skyflowId"); } return data.get("skyflow_id"); } - - public static void validateGetDetectRunRequest(GetDetectRunRequest request) throws SkyflowException { - if (request == null) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); - } - - String runId = request.getRunId(); - if (runId == null || runId.trim().isEmpty()) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidOrEmptyRunId.getMessage()); - } - } } diff --git a/skyvault/src/main/java/com/skyflow/vault/controller/DetectController.java b/skyvault/src/main/java/com/skyflow/vault/controller/DetectController.java index 8fc8ac66..c78fb6ba 100644 --- a/skyvault/src/main/java/com/skyflow/vault/controller/DetectController.java +++ b/skyvault/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -1,453 +1,43 @@ package com.skyflow.vault.controller; -import com.google.gson.*; -import com.skyflow.VaultClient; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.DeidentifyFileStatus; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.resources.files.requests.*; -import com.skyflow.generated.rest.types.*; -import com.skyflow.generated.rest.core.ApiClientApiException; -import com.skyflow.generated.rest.core.ApiClientException; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; -import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; -import com.skyflow.logs.ErrorLogs; -import com.skyflow.logs.InfoLogs; -import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; -import com.skyflow.utils.logger.LogUtil; -import com.skyflow.utils.validations.Validations; -import com.skyflow.vault.detect.*; -import com.skyflow.vault.detect.DeidentifyFileRequest; -import com.skyflow.vault.detect.DeidentifyFileResponse; -import com.skyflow.vault.detect.DeidentifyTextRequest; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.*; -public final class DetectController extends VaultClient { - Gson gson = new GsonBuilder() - .registerTypeAdapter(Optional.class, (JsonSerializer>) (src, typeOfSrc, context) -> - src.map(context::serialize).orElse(null)) - .serializeNulls() - .create(); - private static final JsonObject SKY_METADATA = Utils.getMetrics(); +/** + * Skyflow Detect operations for a skyvault vault, returned by {@code Skyflow.detect()} and + * {@code Skyflow.detect(vaultId)}. Every Detect V2 method ({@code deidentifyString}, + * {@code deidentifyFile}, {@code reidentifyString}, {@code getRun}, {@code checkGuardrails}) is + * inherited from {@link BaseDetectController} and shared with the flowvault SDK; this class only + * supplies the skyvault URL rule and SDK metrics. + * + *

                                  For skyvault vaults a {@code VAULT_TOKEN} entity's {@code destination} is a {@code table.column} + * pair, and {@code RedactionLevel} rules use {@code entityName} and {@code redactionType}. + */ +public final class DetectController extends BaseDetectController { + private final String vaultUrlOverride; public DetectController(VaultConfig vaultConfig, Credentials credentials) { - super(vaultConfig, credentials); - } - - public DeidentifyTextResponse deidentifyText(DeidentifyTextRequest deidentifyTextRequest) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_TRIGGERED.getLog()); - DeidentifyStringResponse deidentifyStringResponse = null; - DeidentifyTextResponse deidentifyTextResponse = null; - try { - // Validate the request - LogUtil.printInfoLog(InfoLogs.VALIDATE_DEIDENTIFY_TEXT_REQUEST.getLog()); - Validations.validateDeidentifyTextRequest(deidentifyTextRequest); - setBearerToken(); - - // Parse the request to DeidentifyStringRequest - String vaultId = super.getVaultConfig().getVaultId(); - DeidentifyStringRequest request = getDeidentifyStringRequest(deidentifyTextRequest, vaultId); - - // get SDK metrics and call the API to de-identify the string - RequestOptions requestOptions = RequestOptions.builder().addHeader(Constants.SDK_METRICS_HEADER_KEY, SKY_METADATA.toString()).build(); - deidentifyStringResponse = super.getDetectTextApi().deidentifyString(request, requestOptions); - - // Parse the response to DeIdentifyTextResponse - deidentifyTextResponse = getDeIdentifyTextResponse(deidentifyStringResponse); - LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_REQUEST_RESOLVED.getLog()); - } catch (ApiClientApiException ex) { - String bodyString = extractBodyAsString(ex); - LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_TEXT_REQUEST_REJECTED.getLog()); - throw new SkyflowException(ex.statusCode(), ex, ex.headers(), bodyString); - } catch (ApiClientException ex) { - throw new SkyflowException(ex); - } - LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_SUCCESS.getLog()); - return deidentifyTextResponse; - } - - public ReidentifyTextResponse reidentifyText(ReidentifyTextRequest reidentifyTextRequest) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_TRIGGERED.getLog()); - ReidentifyTextResponse reidentifyTextResponse = null; - try { - // Validate the request - LogUtil.printInfoLog(InfoLogs.VALIDATE_REIDENTIFY_TEXT_REQUEST.getLog()); - Validations.validateReidentifyTextRequest(reidentifyTextRequest); - setBearerToken(); - // Parse the request to ReidentifyTextRequest - String vaultId = super.getVaultConfig().getVaultId(); - ReidentifyStringRequest request = getReidentifyStringRequest(reidentifyTextRequest, vaultId); - - // Get SDK metrics and call the API to re-identify the string - RequestOptions requestOptions = RequestOptions.builder().addHeader(Constants.SDK_METRICS_HEADER_KEY, SKY_METADATA.toString()).build(); - IdentifyResponse reidentifyStringResponse = super.getDetectTextApi().reidentifyString(request, requestOptions); - - // Parse the response to ReidentifyTextResponse - reidentifyTextResponse = new ReidentifyTextResponse(reidentifyStringResponse.getText()); - LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_REQUEST_RESOLVED.getLog()); - } catch (ApiClientApiException ex) { - String bodyString = extractBodyAsString(ex); - LogUtil.printErrorLog(ErrorLogs.REIDENTIFY_TEXT_REQUEST_REJECTED.getLog()); - throw new SkyflowException(ex.statusCode(), ex, ex.headers(), bodyString); - } catch (ApiClientException ex) { - throw new SkyflowException(ex); - } - LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_SUCCESS.getLog()); - return reidentifyTextResponse; - } - - public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request) throws SkyflowException { - DeidentifyFileResponse response; - LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_FILE_TRIGGERED.getLog()); - try { - LogUtil.printInfoLog(InfoLogs.VALIDATE_DEIDENTIFY_FILE_REQUEST.getLog()); - Validations.validateDeidentifyFileRequest(request); - setBearerToken(); - - String vaultId = super.getVaultConfig().getVaultId(); - - File file; - if (request.getFileInput().getFilePath() != null) { - file = new File(request.getFileInput().getFilePath()); - } else { - file = request.getFileInput().getFile(); - } - String fileName = file.getName(); - String fileExtension = getFileExtension(fileName); - String base64Content; - - try { - base64Content = encodeFileToBase64(file); - } catch (IOException ioe) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedToEncodeFile.getMessage()); - } - - - com.skyflow.generated.rest.types.DeidentifyFileResponse apiResponse = processFileByType(fileExtension, base64Content, request, vaultId); - try { - response = pollForResults(apiResponse.getRunId().get(), request.getWaitTime()); - } catch (Exception ex) { - throw new SkyflowException(ErrorCode.SERVER_ERROR.getCode(), ErrorMessage.PollingForResultsFailed.getMessage()); - } - - if (DeidentifyFileStatus.SUCCESS.value().equalsIgnoreCase(response.getStatus())) { - String base64File = response.getFileBase64(); - if (base64File != null) { - byte[] decodedBytes = Base64.getDecoder().decode(base64File); - String outputDir = request.getOutputDirectory(); - String outputFileName = Constants.PROCESSED_FILE_NAME_PREFIX + getBaseFileName(fileName) + "." + response.getExtension(); - File outputFile; - if (outputDir != null && !outputDir.isEmpty()) { - outputFile = new File(outputDir, outputFileName); - } else { - outputFile = new File(outputFileName); - } - try { - java.nio.file.Files.write(outputFile.toPath(), decodedBytes); - } catch (IOException ioe) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedToSaveProcessedFile.getMessage()); - } - - } - - List entities = response.getEntities(); - if (entities != null && !entities.isEmpty()) { - FileEntityInfo entityInfo = entities.get(0); - String entityBase64 = entityInfo.getFile(); - String outputDir = request.getOutputDirectory(); - if (entityBase64 != null) { - byte[] entityDecodedBytes = Base64.getDecoder().decode(entityBase64); - String entityFileName = Constants.PROCESSED_FILE_NAME_PREFIX + getBaseFileName(fileName) + ".json"; - File entityFile; - if (outputDir != null && !outputDir.isEmpty()) { - entityFile = new File(outputDir, entityFileName); - } else { - entityFile = new File(entityFileName); - } - try { - java.nio.file.Files.write(entityFile.toPath(), entityDecodedBytes); - } catch (IOException ioe) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedToSaveProcessedFile.getMessage()); - } - } - } - } - } catch (ApiClientApiException e) { - String bodyString = extractBodyAsString(e); - LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_FILE_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); - } catch (ApiClientException e) { - throw new SkyflowException(e); - } - return response; - } - - private String getFileExtension(String fileName) { - return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); - } - - private String getBaseFileName(String fileName) { - int dotIndex = fileName.lastIndexOf('.'); - return dotIndex == -1 ? fileName : fileName.substring(0, dotIndex); - } - - private String encodeFileToBase64(File file) throws IOException { - byte[] fileContent = Files.readAllBytes(file.toPath()); - return Base64.getEncoder().encodeToString(fileContent); - } - - private DeidentifyFileResponse pollForResults(String runId, Integer maxWaitTime) throws Exception { - int currentWaitTime = 1; - maxWaitTime = maxWaitTime == null ? 64 : maxWaitTime; - - DetectRunsResponse response = null; - - while (true) { - try { - GetRunRequest getRunRequest = GetRunRequest.builder() - .vaultId(super.getVaultConfig().getVaultId()) - .build(); - - RequestOptions requestOptions = RequestOptions.builder().addHeader(Constants.SDK_METRICS_HEADER_KEY, SKY_METADATA.toString()).build(); - response = super.getDetectFileAPi() - .getRun(runId, getRunRequest, requestOptions); - - DetectRunsResponseStatus status = response.getStatus().orElse(null); - - if (DeidentifyFileStatus.IN_PROGRESS.value().equalsIgnoreCase(String.valueOf(status))) { - if (currentWaitTime >= maxWaitTime) { - return new DeidentifyFileResponse(runId, DeidentifyFileStatus.IN_PROGRESS.value()); - } - - int nextWaitTime = currentWaitTime * 2; - int waitTime; - - if (nextWaitTime >= maxWaitTime) { - waitTime = maxWaitTime - currentWaitTime; - currentWaitTime = maxWaitTime; - } else { - waitTime = nextWaitTime; - currentWaitTime = nextWaitTime; - } - - Thread.sleep(waitTime * 1000); - - } else if (status == DetectRunsResponseStatus.SUCCESS || - status == DetectRunsResponseStatus.FAILED) { - return parseDeidentifyFileResponse(response, runId, status.toString()); - } - } catch (ApiClientApiException e) { - String bodyString = gson.toJson(e.body()); - LogUtil.printErrorLog(ErrorLogs.GET_DETECT_RUN_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); - } catch (ApiClientException e) { - throw new SkyflowException(e); - } - } - - } - - private static synchronized DeidentifyFileResponse parseDeidentifyFileResponse(DetectRunsResponse response, - String runId, String status) throws SkyflowException { - - DeidentifiedFileOutput firstOutput = getFirstOutput(response); - - if (firstOutput == null) { - return new DeidentifyFileResponse( - null, - null, - response.getOutputType().map(Object::toString).orElse(null), - null, - null, - null, - response.getSize().orElse(null), - response.getDuration().orElse(null), - response.getPages().orElse(null), - response.getSlides().orElse(null), - getEntities(response), - runId, - response.getStatus().map(Enum::name).orElse(null) - ); - } - - Integer wordCount = null; - Integer charCount = null; - - WordCharacterCount wordCharacterCount = response.getWordCharacterCount().orElse(null); - if (wordCharacterCount != null) { - wordCount = wordCharacterCount.getWordCount().orElse(null); - charCount = wordCharacterCount.getCharacterCount().orElse(null); - } - - File processedFileObject = null; - FileInfo fileInfo = null; - Optional processedFileBase64 = Optional.of(firstOutput).flatMap(DeidentifiedFileOutput::getProcessedFile); - Optional - processedFileExtension = Optional.of(firstOutput).flatMap(DeidentifiedFileOutput::getProcessedFileExtension); - if (processedFileBase64.isPresent() && processedFileExtension.isPresent()) { - try { - byte[] decodedBytes = Base64.getDecoder().decode(processedFileBase64.get()); - String suffix = "." + processedFileExtension.get(); - String fileName = Constants.DEIDENTIFIED_FILE_PREFIX + suffix; - processedFileObject = new File(System.getProperty("java.io.tmpdir"), fileName); - Files.write(processedFileObject.toPath(), decodedBytes); - fileInfo = new FileInfo(processedFileObject); - processedFileObject.deleteOnExit(); - } catch (IOException ioe) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedToEncodeFile.getMessage()); - } - } - - String processedFileType = firstOutput.getProcessedFileType() - .map(Object::toString) - .orElse(DetectRunsResponseStatus.UNKNOWN.toString()); - - String fileExtension = processedFileExtension - .map(Object::toString) - .orElse(DetectRunsResponseStatus.UNKNOWN.toString()); - Float sizeInKb = response.getSize().orElse(null); - Float durationInSeconds = response.getDuration().orElse(null); - DeidentifyFileResponse deidentifyFileResponse = new DeidentifyFileResponse( - fileInfo, - firstOutput.getProcessedFile().orElse(null), - processedFileType, - fileExtension, - wordCount, - charCount, - sizeInKb, - durationInSeconds, - response.getPages().orElse(null), - response.getSlides().orElse(null), - getEntities(response), - runId, - status - ); - - return deidentifyFileResponse; - } - - private static synchronized DeidentifiedFileOutput getFirstOutput(DetectRunsResponse response) { - List outputs = response.getOutput().orElse(null); - return outputs != null && !outputs.isEmpty() ? outputs.get(0) : null; + this(vaultConfig, credentials, null); } - private static synchronized List getEntities(DetectRunsResponse response) { - List entities = new ArrayList<>(); - - List outputs = response.getOutput().orElse(null); - DeidentifiedFileOutput deidentifyFileOutput = outputs != null && !outputs.isEmpty() ? outputs.get(0) : null; - - if (deidentifyFileOutput != null) { - entities.add(new FileEntityInfo( - deidentifyFileOutput.getProcessedFile().orElse(null), - deidentifyFileOutput.getProcessedFileType().orElse(null), - deidentifyFileOutput.getProcessedFileExtension().orElse(null) - )); - } - - return entities; - } - - private String extractBodyAsString(ApiClientApiException e) { - return e.statusCode() == 500 - ? e.body().toString() - : gson.toJson(e.body()); + /** Test seam: points the controller at an explicit base URL instead of the cluster-derived one. */ + DetectController(VaultConfig vaultConfig, Credentials credentials, String vaultUrlOverride) { + super(vaultConfig, credentials); + this.vaultUrlOverride = vaultUrlOverride; } - - private com.skyflow.generated.rest.types.DeidentifyFileResponse processFileByType(String fileExtension, String base64Content, DeidentifyFileRequest request, String vaultId) throws SkyflowException { - switch (fileExtension.toLowerCase()) { - case "txt": - DeidentifyFileRequestDeidentifyText textFileRequest = - super.getDeidentifyTextFileRequest(request, vaultId, base64Content); - return super.getDetectFileAPi().deidentifyText(textFileRequest); - - case "mp3": - case "wav": - DeidentifyFileAudioRequestDeidentifyAudio audioRequest = - super.getDeidentifyAudioRequest(request, vaultId, base64Content, fileExtension); - return super.getDetectFileAPi().deidentifyAudio(audioRequest); - - case "pdf": - DeidentifyFileDocumentPdfRequestDeidentifyPdf pdfRequest = - super.getDeidentifyPdfRequest(request, vaultId, base64Content); - - return super.getDetectFileAPi().deidentifyPdf(pdfRequest); - - case "jpg": - case "jpeg": - case "png": - case "bmp": - case "tif": - case "tiff": - DeidentifyFileImageRequestDeidentifyImage imageRequest = - super.getDeidentifyImageRequest(request, vaultId, base64Content, fileExtension); - return super.getDetectFileAPi().deidentifyImage(imageRequest); - - case "ppt": - case "pptx": - DeidentifyFileRequestDeidentifyPresentation presentationRequest = - super.getDeidentifyPresentationRequest(request, vaultId, base64Content, fileExtension); - return super.getDetectFileAPi().deidentifyPresentation(presentationRequest); - - case "csv": - case "xls": - case "xlsx": - DeidentifyFileRequestDeidentifySpreadsheet spreadsheetRequest = - super.getDeidentifySpreadsheetRequest(request, vaultId, base64Content, fileExtension); - return super.getDetectFileAPi().deidentifySpreadsheet(spreadsheetRequest); - - case "doc": - case "docx": - DeidentifyFileRequestDeidentifyDocument documentRequest = - super.getDeidentifyDocumentRequest(request, vaultId, base64Content, fileExtension); - return super.getDetectFileAPi().deidentifyDocument(documentRequest); - - case "json": - case "xml": - DeidentifyFileRequestDeidentifyStructuredText structuredTextRequest = - super.getDeidentifyStructuredTextRequest(request, vaultId, base64Content, fileExtension); - return super.getDetectFileAPi().deidentifyStructuredText(structuredTextRequest); - - default: - com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest genericFileRequest = - super.getDeidentifyGenericFileRequest(request, vaultId, base64Content, fileExtension); - return super.getDetectFileAPi().deidentifyFile(genericFileRequest); + @Override + protected String resolveVaultUrl() throws SkyflowException { + if (vaultUrlOverride != null) { + return vaultUrlOverride; } + return Utils.getVaultURL(getVaultConfig().getClusterId(), getVaultConfig().getEnv()); } - public DeidentifyFileResponse getDetectRun(GetDetectRunRequest request) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GET_DETECT_RUN_TRIGGERED.getLog()); - try { - LogUtil.printInfoLog(InfoLogs.VALIDATE_GET_DETECT_RUN_REQUEST.getLog()); - Validations.validateGetDetectRunRequest(request); - setBearerToken(); - String runId = request.getRunId(); - String vaultId = super.getVaultConfig().getVaultId(); - - GetRunRequest getRunRequest = - GetRunRequest.builder() - .vaultId(vaultId) - .build(); - - DetectRunsResponse apiResponse = - super.getDetectFileAPi().getRun(runId, getRunRequest); - - return parseDeidentifyFileResponse(apiResponse, runId, apiResponse.getStatus().toString()); - } catch (ApiClientApiException e) { - String bodyString = extractBodyAsString(e); - LogUtil.printErrorLog(ErrorLogs.GET_DETECT_RUN_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); - } catch (ApiClientException e) { - throw new SkyflowException(e); - } + @Override + protected String getSdkMetrics() { + return Utils.getMetrics().toString(); } } diff --git a/skyvault/src/main/java/com/skyflow/vault/controller/VaultController.java b/skyvault/src/main/java/com/skyflow/vault/controller/VaultController.java index 94d081a3..b3f9623b 100644 --- a/skyvault/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/skyvault/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -27,30 +27,28 @@ import com.skyflow.generated.rest.core.ApiClientException; import com.skyflow.generated.rest.core.ApiClientHttpResponse; import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkDeleteRecordBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkGetRecordRequest; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; -import com.skyflow.generated.rest.resources.records.requests.UploadFileV2Request; -import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestOrderBy; -import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestRedaction; -import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; -import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; -import com.skyflow.generated.rest.types.UploadFileV2Response; -import com.skyflow.generated.rest.types.V1BatchOperationResponse; -import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; -import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; -import com.skyflow.generated.rest.types.V1DetokenizeRecordResponse; -import com.skyflow.generated.rest.types.V1DetokenizeResponse; -import com.skyflow.generated.rest.types.V1FieldRecords; -import com.skyflow.generated.rest.types.V1GetQueryResponse; -import com.skyflow.generated.rest.types.V1InsertRecordResponse; -import com.skyflow.generated.rest.types.V1RecordMetaProperties; -import com.skyflow.generated.rest.types.V1TokenizeRecordResponse; -import com.skyflow.generated.rest.types.V1TokenizeResponse; -import com.skyflow.generated.rest.types.V1UpdateRecordResponse; +import com.skyflow.generated.rest.resources.files.requests.UploadFileRequestV2; +import com.skyflow.generated.rest.resources.query.requests.GetQueryRequest; +import com.skyflow.generated.rest.resources.records.requests.BatchOperationRequest; +import com.skyflow.generated.rest.resources.records.requests.BulkDeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordsRequest; +import com.skyflow.generated.rest.resources.records.requests.InsertRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.UpdateRecordRequest; +import com.skyflow.generated.rest.resources.records.types.GetRecordsRequestOrderBy; +import com.skyflow.generated.rest.resources.records.types.GetRecordsRequestRedaction; +import com.skyflow.generated.rest.resources.tokens.requests.DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.TokenizePayload; +import com.skyflow.generated.rest.types.BatchOperationResponse; +import com.skyflow.generated.rest.types.BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.BulkGetRecordResponse; +import com.skyflow.generated.rest.types.FieldRecords; +import com.skyflow.generated.rest.types.GetFieldRecords; +import com.skyflow.generated.rest.types.GetQueryResponse; +import com.skyflow.generated.rest.types.InsertRecordResponse; +import com.skyflow.generated.rest.types.RecordMetaProperties; +import com.skyflow.generated.rest.types.TokenizeRecordResponse; +import com.skyflow.generated.rest.types.UpdateRecordResponse; +import com.skyflow.generated.rest.types.UploadFileResponseV2; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; import com.skyflow.utils.Constants; @@ -136,7 +134,7 @@ private static synchronized HashMap getFormattedBatchInsertRecor return insertRecord; } - private static synchronized HashMap getFormattedBulkInsertRecord(V1RecordMetaProperties record) { + private static synchronized HashMap getFormattedBulkInsertRecord(RecordMetaProperties record) { HashMap insertRecord = new HashMap<>(); if (record.getSkyflowId().isPresent()) { insertRecord.put("skyflowId", record.getSkyflowId().get()); @@ -149,7 +147,7 @@ private static synchronized HashMap getFormattedBulkInsertRecord return insertRecord; } - private static synchronized HashMap getFormattedGetRecord(V1FieldRecords record) { + private static synchronized HashMap getFormattedGetRecord(GetFieldRecords record) { HashMap getRecord = new HashMap<>(); Optional> fieldsOpt = record.getFields(); @@ -169,7 +167,7 @@ private static synchronized HashMap getFormattedGetRecord(V1Fiel return getRecord; } - private static synchronized HashMap getFormattedUpdateRecord(V1UpdateRecordResponse record) { + private static synchronized HashMap getFormattedUpdateRecord(UpdateRecordResponse record) { HashMap updateTokens = new HashMap<>(); record.getSkyflowId().ifPresent(skyflowId -> updateTokens.put("skyflowId", skyflowId)); @@ -179,7 +177,7 @@ private static synchronized HashMap getFormattedUpdateRecord(V1U return updateTokens; } - private static synchronized HashMap getFormattedQueryRecord(V1FieldRecords record) { + private static synchronized HashMap getFormattedQueryRecord(FieldRecords record) { HashMap queryRecord = new HashMap<>(); Optional> fieldsOpt = record.getFields(); if (fieldsOpt.isPresent()) { @@ -197,8 +195,8 @@ private static synchronized HashMap getFormattedQueryRecord(V1Fi @Override public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.INSERT_TRIGGERED.getLog()); - V1InsertRecordResponse bulkInsertResult = null; - ApiClientHttpResponse batchInsertResult = null; + InsertRecordResponse bulkInsertResult = null; + ApiClientHttpResponse batchInsertResult = null; ArrayList> insertedFields = new ArrayList<>(); ArrayList> errorFields = new ArrayList<>(); try { @@ -207,9 +205,9 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio Boolean continueOnError = insertRequest.getContinueOnError(); setBearerToken(); if (continueOnError) { - RecordServiceBatchOperationBody insertBody = super.getBatchInsertRequestBody(insertRequest); + BatchOperationRequest insertBody = super.getBatchInsertRequestBody(insertRequest); RequestOptions requestOptions = buildRequestOptions(); - batchInsertResult = super.getRecordsApi().withRawResponse().recordServiceBatchOperation(super.getVaultConfig().getVaultId(), insertBody, requestOptions); + batchInsertResult = super.getRecordsApi().withRawResponse().batchOperation(super.getVaultConfig().getVaultId(), insertBody, requestOptions); LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); Optional>> records = batchInsertResult.body().getResponses(); @@ -230,13 +228,13 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio } } } else { - RecordServiceInsertRecordBody insertBody = super.getBulkInsertRequestBody(insertRequest); - bulkInsertResult = super.getRecordsApi().recordServiceInsertRecord( + InsertRecordRequest insertBody = super.getBulkInsertRequestBody(insertRequest); + bulkInsertResult = super.getRecordsApi().insertRecords( super.getVaultConfig().getVaultId(), insertRequest.getTable(), insertBody); LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); - Optional> records = bulkInsertResult.getRecords(); + Optional> records = bulkInsertResult.getRecords(); if (records.isPresent()) { - for (V1RecordMetaProperties record : records.get()) { + for (RecordMetaProperties record : records.get()) { HashMap insertRecord = getFormattedBulkInsertRecord(record); insertedFields.add(insertRecord); } @@ -259,25 +257,25 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.DETOKENIZE_TRIGGERED.getLog()); - ApiClientHttpResponse result = null; + ApiClientHttpResponse result = null; ArrayList detokenizedFields = new ArrayList<>(); ArrayList errorRecords = new ArrayList<>(); try { LogUtil.printInfoLog(InfoLogs.VALIDATE_DETOKENIZE_REQUEST.getLog()); Validations.validateDetokenizeRequest(detokenizeRequest); setBearerToken(); - V1DetokenizePayload payload = super.getDetokenizePayload(detokenizeRequest); + DetokenizePayload payload = super.getDetokenizePayload(detokenizeRequest); RequestOptions requestOptions = buildRequestOptions(); - result = super.getTokensApi().withRawResponse().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload, requestOptions); + result = super.getTokensApi().withRawResponse().detokenize(super.getVaultConfig().getVaultId(), payload, requestOptions); LogUtil.printInfoLog(InfoLogs.DETOKENIZE_REQUEST_RESOLVED.getLog()); Map> responseHeaders = result.headers(); String requestId = extractRequestId(responseHeaders); - Optional> records = result.body().getRecords(); + Optional> records = result.body().getRecords(); if (records.isPresent()) { - List recordList = records.get(); + List recordList = records.get(); - for (V1DetokenizeRecordResponse record : recordList) { + for (com.skyflow.generated.rest.types.DetokenizeRecordResponse record : recordList) { if (record.getError().isPresent()) { DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record, requestId); errorRecords.add(recordResponse); @@ -309,7 +307,7 @@ public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws public GetResponse get(GetRequest getRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.GET_TRIGGERED.getLog()); - V1BulkGetRecordResponse result = null; + BulkGetRecordResponse result = null; ArrayList> data = new ArrayList<>(); ArrayList> errors = new ArrayList<>(); try { @@ -317,9 +315,9 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { Validations.validateGetRequest(getRequest); setBearerToken(); RedactionType redactionType = getRequest.getRedactionType(); - RecordServiceBulkGetRecordRequest recordServiceBulkGetRecordRequest = RecordServiceBulkGetRecordRequest.builder() + GetRecordsRequest getRecordsRequest = GetRecordsRequest.builder() .skyflowIds(getRequest.getIds()) - .redaction(redactionType != null ? RecordServiceBulkGetRecordRequestRedaction.valueOf(redactionType.toString()) : null) + .redaction(redactionType != null ? GetRecordsRequestRedaction.valueOf(redactionType.toString()) : null) .tokenization(getRequest.getReturnTokens()) .offset(getRequest.getOffset()) .limit(getRequest.getLimit()) @@ -327,20 +325,20 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { .columnName(getRequest.getColumnName()) .columnValues(getRequest.getColumnValues()) .fields(getRequest.getFields()) - .orderBy(RecordServiceBulkGetRecordRequestOrderBy.valueOf(getRequest.getOrderBy())) + .orderBy(GetRecordsRequestOrderBy.valueOf(getRequest.getOrderBy())) .build(); RequestOptions requestOptions = buildRequestOptions(); - result = super.getRecordsApi().recordServiceBulkGetRecord( + result = super.getRecordsApi().getRecords( super.getVaultConfig().getVaultId(), getRequest.getTable(), - recordServiceBulkGetRecordRequest, + getRecordsRequest, requestOptions ); LogUtil.printInfoLog(InfoLogs.GET_REQUEST_RESOLVED.getLog()); if (result.getRecords().isPresent()) { - List records = result.getRecords().get(); - for (V1FieldRecords record : records) { + List records = result.getRecords().get(); + for (GetFieldRecords record : records) { data.add(getFormattedGetRecord(record)); } } @@ -355,16 +353,16 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.UPDATE_TRIGGERED.getLog()); - V1UpdateRecordResponse result; + UpdateRecordResponse result; String skyflowId; HashMap tokensMap; try { LogUtil.printInfoLog(InfoLogs.VALIDATE_UPDATE_REQUEST.getLog()); Validations.validateUpdateRequest(updateRequest); setBearerToken(); - RecordServiceUpdateRecordBody updateBody = super.getUpdateRequestBody(updateRequest); + UpdateRecordRequest updateBody = super.getUpdateRequestBody(updateRequest); RequestOptions requestOptions = buildRequestOptions(); - result = super.getRecordsApi().recordServiceUpdateRecord( + result = super.getRecordsApi().updateRecord( super.getVaultConfig().getVaultId(), updateRequest.getTable(), extractUpdateSkyflowId(updateRequest.getData()), @@ -385,16 +383,16 @@ public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowExceptio public DeleteResponse delete(DeleteRequest deleteRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.DELETE_TRIGGERED.getLog()); - V1BulkDeleteRecordResponse result; + BulkDeleteRecordResponse result; try { LogUtil.printInfoLog(InfoLogs.VALIDATING_DELETE_REQUEST.getLog()); Validations.validateDeleteRequest(deleteRequest); setBearerToken(); - RecordServiceBulkDeleteRecordBody deleteBody = RecordServiceBulkDeleteRecordBody.builder().skyflowIds(deleteRequest.getIds()) + BulkDeleteRecordRequest deleteBody = BulkDeleteRecordRequest.builder().skyflowIds(deleteRequest.getIds()) .build(); RequestOptions requestOptions = buildRequestOptions(); - result = super.getRecordsApi().recordServiceBulkDeleteRecord( + result = super.getRecordsApi().deleteRecords( super.getVaultConfig().getVaultId(), deleteRequest.getTable(), deleteBody, requestOptions); LogUtil.printInfoLog(InfoLogs.DELETE_REQUEST_RESOLVED.getLog()); } catch (ApiClientApiException e) { @@ -408,22 +406,22 @@ public DeleteResponse delete(DeleteRequest deleteRequest) throws SkyflowExceptio public QueryResponse query(QueryRequest queryRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.QUERY_TRIGGERED.getLog()); - V1GetQueryResponse result; + GetQueryResponse result; ArrayList> fields = new ArrayList<>(); try { LogUtil.printInfoLog(InfoLogs.VALIDATING_QUERY_REQUEST.getLog()); Validations.validateQueryRequest(queryRequest); setBearerToken(); RequestOptions requestOptions = buildRequestOptions(); - result = super.getQueryApi().queryServiceExecuteQuery( + result = super.getQueryApi().executeQuery( super.getVaultConfig().getVaultId(), - QueryServiceExecuteQueryBody.builder().query(queryRequest.getQuery()).build(), + GetQueryRequest.builder().query(queryRequest.getQuery()).build(), requestOptions ); LogUtil.printInfoLog(InfoLogs.QUERY_REQUEST_RESOLVED.getLog()); if (result.getRecords().isPresent()) { - List records = result.getRecords().get(); // Extract the List from Optional - for (V1FieldRecords record : records) { + List records = result.getRecords().get(); // Extract the List from Optional + for (FieldRecords record : records) { fields.add(getFormattedQueryRecord(record)); } } @@ -438,20 +436,20 @@ public QueryResponse query(QueryRequest queryRequest) throws SkyflowException { public TokenizeResponse tokenize(TokenizeRequest tokenizeRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.TOKENIZE_TRIGGERED.getLog()); - V1TokenizeResponse result = null; + com.skyflow.generated.rest.types.TokenizeResponse result = null; List list = new ArrayList<>(); try { LogUtil.printInfoLog(InfoLogs.VALIDATING_TOKENIZE_REQUEST.getLog()); Validations.validateTokenizeRequest(tokenizeRequest); setBearerToken(); - V1TokenizePayload payload = super.getTokenizePayload(tokenizeRequest); + TokenizePayload payload = super.getTokenizePayload(tokenizeRequest); RequestOptions requestOptions = buildRequestOptions(); - result = super.getTokensApi().recordServiceTokenize(super.getVaultConfig().getVaultId(), payload, requestOptions); + result = super.getTokensApi().tokenize(super.getVaultConfig().getVaultId(), payload, requestOptions); LogUtil.printInfoLog(InfoLogs.TOKENIZE_REQUEST_RESOLVED.getLog()); - if (result != null && result.getRecords().isPresent() && !result.getRecords().get().isEmpty()) { - for (V1TokenizeRecordResponse response : result.getRecords().get()) { - if (response.getToken().isPresent()) { - list.add(response.getToken().get()); + if (result != null && result.getRecords() != null && !result.getRecords().isEmpty()) { + for (TokenizeRecordResponse response : result.getRecords()) { + if (response.getToken() != null) { + list.add(response.getToken()); } } } @@ -474,7 +472,7 @@ public FileUploadResponse uploadFile(FileUploadRequest fileUploadRequest) throws setBearerToken(); File file = super.getFileForFileUpload(fileUploadRequest); - UploadFileV2Request uploadFileV2Request = UploadFileV2Request.builder() + UploadFileRequestV2 uploadFileRequest = UploadFileRequestV2.builder() .tableName(fileUploadRequest.getTable()) .columnName(fileUploadRequest.getColumnName()) .skyflowId(fileUploadRequest.getSkyflowId()) @@ -482,15 +480,15 @@ public FileUploadResponse uploadFile(FileUploadRequest fileUploadRequest) throws .build(); RequestOptions requestOptions = buildRequestOptions(); - UploadFileV2Response uploadFileV2Response = super.getRecordsApi().uploadFileV2( + UploadFileResponseV2 uploadFileResponse = super.getFilesApi().uploadFileV2( super.getVaultConfig().getVaultId(), file, - uploadFileV2Request, + uploadFileRequest, requestOptions ); fileUploadResponse = new FileUploadResponse( - uploadFileV2Response.getSkyflowId().orElse(null), + uploadFileResponse.getSkyflowId().orElse(null), null ); diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/AudioBleep.java b/skyvault/src/main/java/com/skyflow/vault/detect/AudioBleep.java deleted file mode 100644 index 1a75f93b..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/AudioBleep.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.skyflow.vault.detect; - -public class AudioBleep { - private final AudioBleepBuilder builder; - - private AudioBleep(AudioBleepBuilder builder) { - this.builder = builder; - } - - public static AudioBleepBuilder builder() { - return new AudioBleepBuilder(); - } - - public Double getGain() { - return this.builder.gain; - } - - public Double getFrequency() { - return this.builder.frequency; - } - - public Double getStartPadding() { - return this.builder.startPadding; - } - - public Double getStopPadding() { - return this.builder.stopPadding; - } - - public static final class AudioBleepBuilder { - private Double gain; - private Double frequency; - private Double startPadding; - private Double stopPadding; - - private AudioBleepBuilder() { - // Default constructor - } - - public AudioBleepBuilder gain(Double gain) { - this.gain = gain; - return this; - } - - public AudioBleepBuilder frequency(Double frequency) { - this.frequency = frequency; - return this; - } - - public AudioBleepBuilder startPadding(Double startPadding) { - this.startPadding = startPadding; - return this; - } - - public AudioBleepBuilder stopPadding(Double stopPadding) { - this.stopPadding = stopPadding; - return this; - } - - public AudioBleep build() { - return new AudioBleep(this); - } - } -} \ No newline at end of file diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/DateTransformation.java b/skyvault/src/main/java/com/skyflow/vault/detect/DateTransformation.java deleted file mode 100644 index 819927d2..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/DateTransformation.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.skyflow.vault.detect; - - -import com.skyflow.enums.DetectEntities; - -import java.util.List; - -public class DateTransformation { - private final int max; - private final int min; - private final List entities; - - public DateTransformation(int max, int min, List entities) { - this.max = max; - this.min = min; - this.entities = entities; - } - - public int getMax() { - return max; - } - - public int getMin() { - return min; - } - - public List getEntities() { - return entities; - } -} diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java b/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java deleted file mode 100644 index 3ebc450e..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.skyflow.vault.detect; - -import com.skyflow.enums.DetectEntities; -import com.skyflow.enums.DetectOutputTranscriptions; -import com.skyflow.enums.MaskingMethod; -import java.util.List; - -public class DeidentifyFileRequest { - private final DeidentifyFileRequestBuilder builder; - - private DeidentifyFileRequest(DeidentifyFileRequestBuilder builder) { - this.builder = builder; - } - - public static DeidentifyFileRequestBuilder builder() { - return new DeidentifyFileRequestBuilder(); - } - - public FileInput getFileInput() { - return this.builder.fileInput; - } - - public List getEntities() { - return this.builder.entities; - } - - public List getAllowRegexList() { - return this.builder.allowRegexList; - } - - public List getRestrictRegexList() { - return this.builder.restrictRegexList; - } - - public TokenFormat getTokenFormat() { - return this.builder.tokenFormat; - } - - public Transformations getTransformations() { - return this.builder.transformations; - } - - public Boolean getOutputProcessedImage() { - return this.builder.outputProcessedImage; - } - - public Boolean getOutputOcrText() { - return this.builder.outputOcrText; - } - - public MaskingMethod getMaskingMethod() { - return this.builder.maskingMethod; - } - - public Number getPixelDensity() { - return this.builder.pixelDensity; - } - - public Number getMaxResolution() { - return this.builder.maxResolution; - } - - public Boolean getOutputProcessedAudio() { - return this.builder.outputProcessedAudio; - } - - public DetectOutputTranscriptions getOutputTranscription() { - return this.builder.outputTranscription; - } - - public AudioBleep getBleep() { - return this.builder.bleep; - } - - public String getOutputDirectory() { - return this.builder.outputDirectory; - } - - public Integer getWaitTime() { - return this.builder.waitTime; - } - - public static final class DeidentifyFileRequestBuilder { - private List entities; - private List allowRegexList; - private List restrictRegexList; - private TokenFormat tokenFormat; - private Transformations transformations; - private Boolean outputProcessedImage; - private Boolean outputOcrText; - private MaskingMethod maskingMethod; - private Number pixelDensity; - private Number maxResolution; - private Boolean outputProcessedAudio; - private DetectOutputTranscriptions outputTranscription; - private AudioBleep bleep; - private FileInput fileInput; - private String outputDirectory; - private Integer waitTime; - - private DeidentifyFileRequestBuilder() { - // Set default values - this.outputProcessedImage = false; - this.outputOcrText = false; - this.outputProcessedAudio = false; - } - - public DeidentifyFileRequestBuilder file(FileInput fileInput) { - this.fileInput = fileInput; - return this; - } - - public DeidentifyFileRequestBuilder entities(List entities) { - this.entities = entities; - return this; - } - - public DeidentifyFileRequestBuilder allowRegexList(List allowRegexList) { - this.allowRegexList = allowRegexList; - return this; - } - - public DeidentifyFileRequestBuilder restrictRegexList(List restrictRegexList) { - this.restrictRegexList = restrictRegexList; - return this; - } - - public DeidentifyFileRequestBuilder tokenFormat(TokenFormat tokenFormat) { - this.tokenFormat = tokenFormat; - return this; - } - - public DeidentifyFileRequestBuilder transformations(Transformations transformations) { - this.transformations = transformations; - return this; - } - - public DeidentifyFileRequestBuilder outputProcessedImage(Boolean outputProcessedImage) { - this.outputProcessedImage = outputProcessedImage != null ? outputProcessedImage : false; - return this; - } - - public DeidentifyFileRequestBuilder outputOcrText(Boolean outputOcrText) { - this.outputOcrText = outputOcrText != null ? outputOcrText : false; - return this; - } - - public DeidentifyFileRequestBuilder maskingMethod(MaskingMethod maskingMethod) { - this.maskingMethod = maskingMethod; - return this; - } - - public DeidentifyFileRequestBuilder pixelDensity(Number pixelDensity) { - this.pixelDensity = pixelDensity; - return this; - } - - public DeidentifyFileRequestBuilder maxResolution(Number maxResolution) { - this.maxResolution = maxResolution; - return this; - } - - public DeidentifyFileRequestBuilder outputProcessedAudio(Boolean outputProcessedAudio) { - this.outputProcessedAudio = outputProcessedAudio != null ? outputProcessedAudio : false; - return this; - } - - public DeidentifyFileRequestBuilder outputTranscription(DetectOutputTranscriptions outputTranscription) { - this.outputTranscription = outputTranscription; - return this; - } - - public DeidentifyFileRequestBuilder bleep(AudioBleep bleep) { - this.bleep = bleep; - return this; - } - - public DeidentifyFileRequestBuilder outputDirectory(String outputDirectory) { - this.outputDirectory = outputDirectory; - return this; - } - - public DeidentifyFileRequestBuilder waitTime(Integer waitTime) { - this.waitTime = waitTime; - return this; - } - - public DeidentifyFileRequest build() { - return new DeidentifyFileRequest(this); - } - } -} \ No newline at end of file diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java b/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java deleted file mode 100644 index 08636d77..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.skyflow.vault.detect; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import java.util.List; - -public class DeidentifyFileResponse { - private final FileInfo file; - private final String fileBase64; - private final String type; - private final String extension; - private final Integer wordCount; - private final Integer charCount; - private final Float sizeInKb; - private final Float durationInSeconds; - private final Integer pageCount; - private final Integer slideCount; - private final List entities; - private final String runId; - private final String status; - - - public DeidentifyFileResponse(FileInfo file, String fileBase64, String type, String extension, - Integer wordCount, Integer charCount, Float sizeInKb, - Float durationInSeconds, Integer pageCount, Integer slideCount, - List entities, String runId, String status) { - this.file = file; - this.fileBase64 = fileBase64; - this.type = type; - this.extension = extension; - this.wordCount = wordCount; - this.charCount = charCount; - this.sizeInKb = sizeInKb; - this.durationInSeconds = durationInSeconds; - this.pageCount = pageCount; - this.slideCount = slideCount; - this.entities = entities; - this.runId = runId; - this.status = status; - } - - public DeidentifyFileResponse(String runId, String status) { - this(null, null, null, null, null, null, null, null, null, null, null, runId, status); - } - - public FileInfo getFile() { - return file; - } - - public String getFileBase64(){ - return fileBase64; - } - - public String getType() { - return type; - } - - public String getExtension() { - return extension; - } - - public Integer getWordCount() { - return wordCount; - } - - public Integer getCharCount() { - return charCount; - } - - public Float getSizeInKb() { - return sizeInKb; - } - - public Float getDurationInSeconds() { - return durationInSeconds; - } - - public Integer getPageCount() { - return pageCount; - } - - public Integer getSlideCount() { - return slideCount; - } - - public List getEntities() { - return entities; - } - - public String getRunId() { - return runId; - } - - public String getStatus() { - return status; - } - - @Override - public String toString() { - Gson gson = new GsonBuilder().serializeNulls().create(); - return gson.toJson(this); - } - -} diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java b/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java deleted file mode 100644 index 5f57e3a9..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.skyflow.vault.detect; - - -import com.skyflow.enums.DetectEntities; - -import java.util.List; - -public class DeidentifyTextRequest { - private final DeidentifyTextRequestBuilder builder; - - private DeidentifyTextRequest(DeidentifyTextRequestBuilder builder) { - this.builder = builder; - } - - public static DeidentifyTextRequestBuilder builder() { - return new DeidentifyTextRequestBuilder(); - } - - public String getText() { - return this.builder.text; - } - - public List getEntities() { - return this.builder.entities; - } - - public List getAllowRegexList() { - return this.builder.allowRegexList; - } - - public List getRestrictRegexList() { - return this.builder.restrictRegexList; - } - - public TokenFormat getTokenFormat() { - return this.builder.tokenFormat; - } - - public Transformations getTransformations() { - return this.builder.transformations; - } - - public static final class DeidentifyTextRequestBuilder { - private String text; - private List entities; - private List allowRegexList; - private List restrictRegexList; - private TokenFormat tokenFormat; - private Transformations transformations; - - private DeidentifyTextRequestBuilder() { - } - - public DeidentifyTextRequestBuilder text(String text) { - this.text = text; - return this; - } - - public DeidentifyTextRequestBuilder entities(List entities) { - this.entities = entities; - return this; - } - - public DeidentifyTextRequestBuilder allowRegexList(List allowRegexList) { - this.allowRegexList = allowRegexList; - return this; - } - - public DeidentifyTextRequestBuilder restrictRegexList(List restrictRegexList) { - this.restrictRegexList = restrictRegexList; - return this; - } - - public DeidentifyTextRequestBuilder tokenFormat(TokenFormat tokenFormat) { - this.tokenFormat = tokenFormat; - return this; - } - - public DeidentifyTextRequestBuilder transformations(Transformations transformations) { - this.transformations = transformations; - return this; - } - - public DeidentifyTextRequest build() { - return new DeidentifyTextRequest(this); - } - } -} \ No newline at end of file diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java b/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java deleted file mode 100644 index 6b6118e0..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.skyflow.vault.detect; - - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import java.util.List; - -public class DeidentifyTextResponse { - private final String processedText; - private final List entities; - private final int wordCount; - private final int charCount; - - public DeidentifyTextResponse(String processedText, List entities, int wordCount, int charCount) { - this.processedText = processedText; - this.entities = entities; - this.wordCount = wordCount; - this.charCount = charCount; - } - - public String getProcessedText() { - return processedText; - } - - public List getEntities() { - return entities; - } - - public int getWordCount() { - return wordCount; - } - - public int getCharCount() { - return charCount; - } - - @Override - public String toString() { - Gson gson = new GsonBuilder().serializeNulls().create(); - return gson.toJson(this); - } - -} diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/EntityInfo.java b/skyvault/src/main/java/com/skyflow/vault/detect/EntityInfo.java deleted file mode 100644 index 4a84acf9..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/EntityInfo.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.skyflow.vault.detect; - - -import java.util.Map; - -public class EntityInfo { - private final String token; - private final String value; - private final TextIndex textIndex; - private final TextIndex processedIndex; - private final String entity; - private final Map scores; - - public EntityInfo(String token, String value, TextIndex textIndex, TextIndex processedIndex, String entity, java.util.Map scores) { - this.token = token; - this.value = value; - this.textIndex = textIndex; - this.processedIndex = processedIndex; - this.entity = entity; - this.scores = scores; - } - - public String getToken() { - return token; - } - - public String getValue() { - return value; - } - - public TextIndex getTextIndex() { - return textIndex; - } - - public TextIndex getProcessedIndex() { - return processedIndex; - } - - public String getEntity() { - return entity; - } - - public Map getScores() { - return scores; - } -} diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java b/skyvault/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java deleted file mode 100644 index 1c41e6ac..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.skyflow.vault.detect; - -import com.skyflow.generated.rest.types.DeidentifiedFileOutputProcessedFileExtension; -import com.skyflow.generated.rest.types.DeidentifiedFileOutputProcessedFileType; - -public class FileEntityInfo { - private final String file; - private final String type; - private final String extension; - - public FileEntityInfo(String file, DeidentifiedFileOutputProcessedFileType type, DeidentifiedFileOutputProcessedFileExtension extension) { - this.file = file; - this.type = String.valueOf(type); - this.extension = String.valueOf(extension); - } - - public String getFile() { return file; } - public String getType() { return type; } - public String getExtension() { return extension; } -} \ No newline at end of file diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/FileInfo.java b/skyvault/src/main/java/com/skyflow/vault/detect/FileInfo.java deleted file mode 100644 index 2f13c4f2..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/FileInfo.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.skyflow.vault.detect; - -import java.io.File; - -public class FileInfo { - private String name; - private long size; - private String type; - private long lastModified; - - public FileInfo(File file) { - this.name = file.getName(); - this.size = file.length(); - this.type = ""; - this.lastModified = file.lastModified(); - } - - public String getName() { - return name; - } - - public long getSize() { - return size; - } - - public String getType() { - return type; - } - - public long getLastModified() { - return lastModified; - } -} diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/FileInput.java b/skyvault/src/main/java/com/skyflow/vault/detect/FileInput.java deleted file mode 100644 index 3ff1a77e..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/FileInput.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.skyflow.vault.detect; - -import java.io.File; - -public class FileInput { - private final FileInputBuilder builder; - - private FileInput(FileInputBuilder builder) { - this.builder = builder; - } - - public static FileInputBuilder builder() { - return new FileInputBuilder(); - } - - public File getFile() { - return this.builder.file; - } - - public String getFilePath() { - return this.builder.filePath; - } - - public static final class FileInputBuilder { - private File file; - private String filePath; - - private FileInputBuilder() { - // Default constructor - } - - public FileInputBuilder file(File file) { - this.file = file; - return this; - } - - public FileInputBuilder filePath(String filePath) { - this.filePath = filePath; - return this; - } - - public FileInput build() { - return new FileInput(this); - } - } -} \ No newline at end of file diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java b/skyvault/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java deleted file mode 100644 index cebec9f2..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.skyflow.vault.detect; - -public class GetDetectRunRequest { - private final String runId; - - private GetDetectRunRequest(GetDetectRunRequestBuilder builder) { - this.runId = builder.runId; - } - - public static GetDetectRunRequestBuilder builder() { - return new GetDetectRunRequestBuilder(); - } - - public String getRunId() { - return this.runId; - } - - public static final class GetDetectRunRequestBuilder { - private String runId; - - private GetDetectRunRequestBuilder() { - } - - public GetDetectRunRequestBuilder runId(String runId) { - this.runId = runId; - return this; - } - - public GetDetectRunRequest build() { - return new GetDetectRunRequest(this); - } - } -} \ No newline at end of file diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java b/skyvault/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java deleted file mode 100644 index cc0e216a..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.skyflow.vault.detect; - - -import com.skyflow.enums.DetectEntities; - -import java.util.List; - -public class ReidentifyTextRequest { - private final ReidentifyTextRequestBuilder builder; - - private ReidentifyTextRequest(ReidentifyTextRequestBuilder builder) { - this.builder = builder; - } - - public static ReidentifyTextRequestBuilder builder() { - return new ReidentifyTextRequestBuilder(); - } - - public String getText() { - return this.builder.text; - } - - public List getRedactedEntities() { - return this.builder.redactedEntities; - } - - public List getMaskedEntities() { - return this.builder.maskedEntities; - } - - public List getPlainTextEntities() { - return this.builder.plainTextEntities; - } - - public static final class ReidentifyTextRequestBuilder { - private String text; - private List redactedEntities; - private List maskedEntities; - private List plainTextEntities; - - private ReidentifyTextRequestBuilder() { - } - - public ReidentifyTextRequestBuilder text(String text) { - this.text = text; - return this; - } - - public ReidentifyTextRequestBuilder redactedEntities(List redactedEntities) { - this.redactedEntities = redactedEntities; - return this; - } - - public ReidentifyTextRequestBuilder maskedEntities(List maskedEntities) { - this.maskedEntities = maskedEntities; - return this; - } - - public ReidentifyTextRequestBuilder plainTextEntities(List plainTextEntities) { - this.plainTextEntities = plainTextEntities; - return this; - } - - public ReidentifyTextRequest build() { - return new ReidentifyTextRequest(this); - } - } -} diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java b/skyvault/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java deleted file mode 100644 index 3a517968..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.skyflow.vault.detect; - - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class ReidentifyTextResponse { - private final String processedText; - - public ReidentifyTextResponse(String processedText) { - this.processedText = processedText; - } - - public String getProcessedText() { - return processedText; - } - - @Override - public String toString() { - Gson gson = new GsonBuilder().serializeNulls().create(); - return gson.toJson(this); - } -} diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/TextIndex.java b/skyvault/src/main/java/com/skyflow/vault/detect/TextIndex.java deleted file mode 100644 index 6fe99c1d..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/TextIndex.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.skyflow.vault.detect; - - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class TextIndex { - private final Integer start; - private final Integer end; - - public TextIndex(Integer start, Integer end) { - this.start = start; - this.end = end; - } - - public int getStart() { - return start; - } - - public int getEnd() { - return end; - } - - @Override - public String toString() { - Gson gson = new GsonBuilder().serializeNulls().create(); - return gson.toJson(this); - } -} diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/TokenFormat.java b/skyvault/src/main/java/com/skyflow/vault/detect/TokenFormat.java deleted file mode 100644 index 8809d0a3..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/TokenFormat.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.skyflow.vault.detect; - - -import com.skyflow.enums.DetectEntities; -import com.skyflow.enums.TokenType; - -import java.util.List; - - -public class TokenFormat { - private final TokenFormatBuilder builder; - - private TokenFormat(TokenFormatBuilder builder) { - this.builder = builder; - } - - public static TokenFormatBuilder builder() { - return new TokenFormatBuilder(); - } - - public TokenType getDefault() { - return this.builder.defaultType; - } - - public List getVaultToken() { - return this.builder.vaultToken; - } - - public List getEntityUniqueCounter() { - return this.builder.entityUniqueCounter; - } - - public List getEntityOnly() { - return this.builder.entityOnly; - } - - public static final class TokenFormatBuilder { - private TokenType defaultType; - private List vaultToken; - private List entityUniqueCounter; - private List entityOnly; - - private TokenFormatBuilder() { - this.defaultType = TokenType.ENTITY_UNIQUE_COUNTER; - } - - public TokenFormatBuilder defaultType(TokenType defaultType) { - this.defaultType = defaultType != null ? defaultType : TokenType.ENTITY_UNIQUE_COUNTER; - return this; - } - - public TokenFormatBuilder vaultToken(List vaultToken) { - this.vaultToken = vaultToken; - return this; - } - - public TokenFormatBuilder entityUniqueCounter(List entityUniqueCounter) { - this.entityUniqueCounter = entityUniqueCounter; - return this; - } - - public TokenFormatBuilder entityOnly(List entityOnly) { - this.entityOnly = entityOnly; - return this; - } - - public TokenFormat build() { - return new TokenFormat(this); - } - } -} \ No newline at end of file diff --git a/skyvault/src/main/java/com/skyflow/vault/detect/Transformations.java b/skyvault/src/main/java/com/skyflow/vault/detect/Transformations.java deleted file mode 100644 index 2e219101..00000000 --- a/skyvault/src/main/java/com/skyflow/vault/detect/Transformations.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.skyflow.vault.detect; - - -public class Transformations { - private final DateTransformation shiftDates; - - public Transformations(DateTransformation shiftDates) { - this.shiftDates = shiftDates; - } - - public DateTransformation getShiftDates() { - return shiftDates; - } -} diff --git a/skyvault/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java b/skyvault/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java index a16b17dd..276e8b87 100644 --- a/skyvault/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java +++ b/skyvault/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java @@ -4,27 +4,43 @@ import com.skyflow.generated.rest.types.V1DetokenizeRecordResponse; import com.skyflow.vault.data.BaseDetokenizeRecordResponse; +import java.util.Optional; + public class DetokenizeRecordResponse extends BaseDetokenizeRecordResponse { private final String type; private final String requestId; private final String value; + public DetokenizeRecordResponse(com.skyflow.generated.rest.types.DetokenizeRecordResponse record) { + this(record, null); + } + + public DetokenizeRecordResponse(com.skyflow.generated.rest.types.DetokenizeRecordResponse record, String requestId) { + this(record.getToken(), record.getError(), record.getValue(), record.getValueType().map(Object::toString), requestId); + } + + /** Kept for binary compatibility with callers built against the previous generated model. */ public DetokenizeRecordResponse(V1DetokenizeRecordResponse record) { this(record, null); } + /** Kept for binary compatibility with callers built against the previous generated model. */ public DetokenizeRecordResponse(V1DetokenizeRecordResponse record, String requestId) { - super(record.getToken().orElse(null), record.getError().orElse(null)); - this.value = record.getValue() - .filter(val -> val != null && !val.toString().isEmpty()) + this(record.getToken(), record.getError(), record.getValue(), record.getValueType().map(Object::toString), requestId); + } + + private DetokenizeRecordResponse(Optional token, Optional error, Optional value, + Optional valueType, String requestId) { + super(token.orElse(null), error.orElse(null)); + this.value = value + .filter(val -> val != null && !val.isEmpty()) .orElse(null); - this.type = record.getValueType() - .map(Enum::toString) + this.type = valueType .filter(val -> !"NONE".equals(val)) .orElse(null); - this.requestId = requestId; } + public String getValue() { return value; } @@ -36,4 +52,4 @@ public String getType() { public String getRequestId() { return requestId; } -} \ No newline at end of file +} diff --git a/skyvault/src/test/java/com/skyflow/RequestFidelityTests.java b/skyvault/src/test/java/com/skyflow/RequestFidelityTests.java index 7dd2cfd0..70f6784f 100644 --- a/skyvault/src/test/java/com/skyflow/RequestFidelityTests.java +++ b/skyvault/src/test/java/com/skyflow/RequestFidelityTests.java @@ -15,34 +15,9 @@ import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.resources.query.QueryClient; -import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; import com.skyflow.generated.rest.resources.records.RawRecordsClient; import com.skyflow.generated.rest.resources.records.RecordsClient; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkDeleteRecordBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkGetRecordRequest; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; -import com.skyflow.generated.rest.resources.records.requests.UploadFileV2Request; -import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestOrderBy; -import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestRedaction; -import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; -import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; import com.skyflow.generated.rest.types.BatchRecordMethod; -import com.skyflow.generated.rest.types.RedactionEnumRedaction; -import com.skyflow.generated.rest.types.UploadFileV2Response; -import com.skyflow.generated.rest.types.V1BatchOperationResponse; -import com.skyflow.generated.rest.types.V1BatchRecord; -import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; -import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; -import com.skyflow.generated.rest.types.V1Byot; -import com.skyflow.generated.rest.types.V1DetokenizeRecordRequest; -import com.skyflow.generated.rest.types.V1FieldRecords; -import com.skyflow.generated.rest.types.V1GetQueryResponse; -import com.skyflow.generated.rest.types.V1InsertRecordResponse; -import com.skyflow.generated.rest.types.V1TokenizeRecordRequest; -import com.skyflow.generated.rest.types.V1TokenizeResponse; -import com.skyflow.generated.rest.types.V1UpdateRecordResponse; import com.skyflow.utils.HttpUtility; import com.skyflow.utils.Utils; import com.skyflow.vault.connection.InvokeConnectionRequest; @@ -85,6 +60,33 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; +import com.skyflow.generated.rest.types.UploadFileResponseV2; +import com.skyflow.generated.rest.types.UpdateRecordResponse; +import com.skyflow.generated.rest.types.TokenizeRecordRequest; +import com.skyflow.generated.rest.types.InsertRecordResponse; +import com.skyflow.generated.rest.types.GetQueryResponse; +import com.skyflow.generated.rest.types.GetFieldRecords; +import com.skyflow.generated.rest.types.FieldRecords; +import com.skyflow.generated.rest.types.DetokenizeRecordRequestRedaction; +import com.skyflow.generated.rest.types.DetokenizeRecordRequest; +import com.skyflow.generated.rest.types.BulkGetRecordResponse; +import com.skyflow.generated.rest.types.BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.BatchRecord; +import com.skyflow.generated.rest.types.BatchOperationResponse; +import com.skyflow.generated.rest.resources.tokens.requests.TokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.DetokenizePayload; +import com.skyflow.generated.rest.resources.records.types.UpdateRecordRequestByot; +import com.skyflow.generated.rest.resources.records.types.InsertRecordRequestByot; +import com.skyflow.generated.rest.resources.records.types.GetRecordsRequestRedaction; +import com.skyflow.generated.rest.resources.records.types.GetRecordsRequestOrderBy; +import com.skyflow.generated.rest.resources.records.requests.UpdateRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.InsertRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.GetRecordsRequest; +import com.skyflow.generated.rest.resources.records.requests.BulkDeleteRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.BatchOperationRequest; +import com.skyflow.generated.rest.resources.query.requests.GetQueryRequest; +import com.skyflow.generated.rest.resources.files.requests.UploadFileRequestV2; +import com.skyflow.generated.rest.resources.files.FilesClient; /** * Request-fidelity tests for the v2 SDK. @@ -197,14 +199,14 @@ public void testInsertBulk_everyBuilderValueReachesGeneratedBody() { .continueOnError(false) .build(); - RecordServiceInsertRecordBody body = client.getBulkInsertRequestBody(request); + InsertRecordRequest body = client.getBulkInsertRequestBody(request); Assert.assertTrue("tokenization must carry returnTokens", body.getTokenization().isPresent()); Assert.assertTrue(body.getTokenization().get()); Assert.assertEquals("email", body.getUpsert().get()); - Assert.assertEquals(V1Byot.ENABLE_STRICT, body.getByot().get()); + Assert.assertEquals(InsertRecordRequestByot.ENABLE_STRICT, body.getByot().get()); - List records = body.getRecords().get(); + List records = body.getRecords(); Assert.assertEquals(2, records.size()); Map fields0 = records.get(0).getFields().get(); @@ -232,7 +234,7 @@ public void testInsertBulk_homogeneousReachesGeneratedBody() { .homogeneous(true) .build(); - RecordServiceInsertRecordBody body = client.getBulkInsertRequestBody(request); + InsertRecordRequest body = client.getBulkInsertRequestBody(request); Assert.assertTrue(body.getHomogeneous().isPresent()); Assert.assertTrue(body.getHomogeneous().get()); } @@ -245,9 +247,9 @@ public void testInsertBulk_defaultsReachGeneratedBody() { .values(rows(richRow())) .build(); - RecordServiceInsertRecordBody body = client.getBulkInsertRequestBody(request); + InsertRecordRequest body = client.getBulkInsertRequestBody(request); Assert.assertFalse("returnTokens defaults to false", body.getTokenization().get()); - Assert.assertEquals("tokenMode defaults to DISABLE -> byot DISABLE", V1Byot.DISABLE, body.getByot().get()); + Assert.assertEquals("tokenMode defaults to DISABLE -> byot DISABLE", InsertRecordRequestByot.DISABLE, body.getByot().get()); Assert.assertFalse("upsert not set -> absent", body.getUpsert().isPresent()); Assert.assertFalse("homogeneous not set -> absent", body.getHomogeneous().isPresent()); } @@ -273,7 +275,7 @@ public void testInsertBulk_tokensPairPositionallyWithValues() { .tokenMode(TokenMode.ENABLE_STRICT) .build(); - List records = client.getBulkInsertRequestBody(request).getRecords().get(); + List records = client.getBulkInsertRequestBody(request).getRecords(); Assert.assertEquals("4111111111111111", records.get(0).getFields().get().get("card_number")); Assert.assertEquals("token-for-row-0", records.get(0).getTokens().get().get("card_number")); @@ -292,7 +294,7 @@ public void testInsertBulk_recordOrderIsPreserved() { } InsertRequest request = InsertRequest.builder().table("cards").values(values).build(); - List records = client.getBulkInsertRequestBody(request).getRecords().get(); + List records = client.getBulkInsertRequestBody(request).getRecords(); Assert.assertEquals(5, records.size()); for (int i = 0; i < 5; i++) { @@ -318,7 +320,7 @@ public void testInsertBulk_fewerTokensThanValuesLeavesTrailingRecordsWithoutToke .tokenMode(TokenMode.ENABLE) .build(); - List records = client.getBulkInsertRequestBody(request).getRecords().get(); + List records = client.getBulkInsertRequestBody(request).getRecords(); Assert.assertEquals(2, records.size()); Assert.assertEquals("token-0", records.get(0).getTokens().get().get("card_number")); Assert.assertFalse("record without a matching token entry gets no tokens", @@ -346,24 +348,25 @@ public void testInsertBatch_everyBuilderValueReachesGeneratedBody() { .continueOnError(true) .build(); - RecordServiceBatchOperationBody body = client.getBatchInsertRequestBody(request); + BatchOperationRequest body = client.getBatchInsertRequestBody(request); Assert.assertTrue("batch body always sends continueOnError=true", body.getContinueOnError().get()); - Assert.assertEquals(V1Byot.ENABLE, body.getByot().get()); + Assert.assertEquals("byot is carried as an extra property on the batch body", "ENABLE", + body.getAdditionalProperties().get("byot")); - List records = body.getRecords().get(); + List records = body.getRecords(); Assert.assertEquals(2, records.size()); - V1BatchRecord first = records.get(0); - Assert.assertEquals("table maps to per-record tableName", "cards", first.getTableName().get()); - Assert.assertEquals(BatchRecordMethod.POST, first.getMethod().get()); + BatchRecord first = records.get(0); + Assert.assertEquals("table maps to per-record tableName", "cards", first.getTableName()); + Assert.assertEquals(BatchRecordMethod.POST, first.getMethod()); Assert.assertEquals("email", first.getUpsert().get()); Assert.assertTrue(first.getTokenization().get()); - Assert.assertEquals("whole values map must be carried verbatim", row1, first.getFields().get()); - Assert.assertEquals(NON_ASCII_NAME, first.getFields().get().get("name")); + Assert.assertEquals("whole values map must be carried verbatim", row1, first.getFields()); + Assert.assertEquals(NON_ASCII_NAME, first.getFields().get("name")); - Assert.assertEquals("cards", records.get(1).getTableName().get()); - Assert.assertEquals("second record", records.get(1).getFields().get().get("name")); + Assert.assertEquals("cards", records.get(1).getTableName()); + Assert.assertEquals("second record", records.get(1).getFields().get("name")); } @Test @@ -390,10 +393,10 @@ public void testInsertBatch_tokensPairPositionallyAndOrderIsPreserved() { .continueOnError(true) .build(); - List records = client.getBatchInsertRequestBody(request).getRecords().get(); + List records = client.getBatchInsertRequestBody(request).getRecords(); Assert.assertEquals(4, records.size()); for (int i = 0; i < 4; i++) { - Assert.assertEquals(i, records.get(i).getFields().get().get("position")); + Assert.assertEquals(i, records.get(i).getFields().get("position")); Assert.assertEquals("token-" + i, records.get(i).getTokens().get().get("position")); } } @@ -408,23 +411,24 @@ public void testInsertBatch_homogeneousIsDropped_knownGap() { InsertRequest bulkRequest = InsertRequest.builder() .table("cards").values(rows(richRow())).homogeneous(true).continueOnError(false).build(); - RecordServiceInsertRecordBody bulkBody = client.getBulkInsertRequestBody(bulkRequest); + InsertRecordRequest bulkBody = client.getBulkInsertRequestBody(bulkRequest); Assert.assertTrue("bulk branch DOES send homogeneous", bulkBody.getHomogeneous().get()); Assert.assertTrue(bulkBody.toString().contains("homogeneous")); InsertRequest batchRequest = InsertRequest.builder() .table("cards").values(rows(richRow())).homogeneous(true).continueOnError(true).build(); - RecordServiceBatchOperationBody batchBody = client.getBatchInsertRequestBody(batchRequest); + BatchOperationRequest batchBody = client.getBatchInsertRequestBody(batchRequest); - for (Method method : RecordServiceBatchOperationBody.class.getMethods()) { + for (Method method : BatchOperationRequest.class.getMethods()) { Assert.assertFalse("batch body has no homogeneous accessor", method.getName().toLowerCase(Locale.ROOT).contains("homogeneous")); } - for (Method method : V1BatchRecord.class.getMethods()) { + for (Method method : BatchRecord.class.getMethods()) { Assert.assertFalse("batch record has no homogeneous accessor", method.getName().toLowerCase(Locale.ROOT).contains("homogeneous")); } - Assert.assertTrue(batchBody.getAdditionalProperties().isEmpty()); + Assert.assertEquals("only byot rides along as an extra property", + Collections.singleton("byot"), batchBody.getAdditionalProperties().keySet()); Assert.assertFalse("homogeneous never reaches the wire on the batch branch", batchBody.toString().contains("homogeneous")); } @@ -434,17 +438,17 @@ public void testInsert_continueOnErrorFalseUsesBulkEndpointWithTableAsPathParam( ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceInsertRecord(anyString(), anyString(), any())) - .thenReturn(V1InsertRecordResponse.builder().build()); + when(mockRecords.insertRecords(anyString(), anyString(), any())) + .thenReturn(InsertRecordResponse.builder().build()); VaultController controller = newControllerWithMockApi(mockApi); InsertRequest request = InsertRequest.builder() .table("cards").values(rows(richRow())).returnTokens(true).continueOnError(false).build(); controller.insert(request); - ArgumentCaptor bodyCaptor = - ArgumentCaptor.forClass(RecordServiceInsertRecordBody.class); - Mockito.verify(mockRecords).recordServiceInsertRecord(eq(VAULT_ID), eq("cards"), bodyCaptor.capture()); + ArgumentCaptor bodyCaptor = + ArgumentCaptor.forClass(InsertRecordRequest.class); + Mockito.verify(mockRecords).insertRecords(eq(VAULT_ID), eq("cards"), bodyCaptor.capture()); Assert.assertTrue(bodyCaptor.getValue().getTokenization().get()); Mockito.verify(mockRecords, Mockito.never()).withRawResponse(); } @@ -456,21 +460,21 @@ public void testInsert_continueOnErrorTrueUsesBatchEndpoint() throws Exception { RawRecordsClient mockRawRecords = Mockito.mock(RawRecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); when(mockRecords.withRawResponse()).thenReturn(mockRawRecords); - when(mockRawRecords.recordServiceBatchOperation(anyString(), any(), any())) + when(mockRawRecords.batchOperation(anyString(), any(), any())) .thenReturn(new com.skyflow.generated.rest.core.ApiClientHttpResponse<>( - V1BatchOperationResponse.builder().build(), buildOkHttpResponse())); + BatchOperationResponse.builder().build(), buildOkHttpResponse())); VaultController controller = newControllerWithMockApi(mockApi); InsertRequest request = InsertRequest.builder() .table("cards").values(rows(richRow())).continueOnError(true).build(); controller.insert(request); - ArgumentCaptor bodyCaptor = - ArgumentCaptor.forClass(RecordServiceBatchOperationBody.class); - Mockito.verify(mockRawRecords).recordServiceBatchOperation(eq(VAULT_ID), bodyCaptor.capture(), any()); + ArgumentCaptor bodyCaptor = + ArgumentCaptor.forClass(BatchOperationRequest.class); + Mockito.verify(mockRawRecords).batchOperation(eq(VAULT_ID), bodyCaptor.capture(), any()); Assert.assertTrue(bodyCaptor.getValue().getContinueOnError().get()); - Assert.assertEquals("cards", bodyCaptor.getValue().getRecords().get().get(0).getTableName().get()); - Mockito.verify(mockRecords, Mockito.never()).recordServiceInsertRecord(anyString(), anyString(), any()); + Assert.assertEquals("cards", bodyCaptor.getValue().getRecords().get(0).getTableName()); + Mockito.verify(mockRecords, Mockito.never()).insertRecords(anyString(), anyString(), any()); } // ================================================================== @@ -482,8 +486,8 @@ public void testUpdate_everyBuilderValueReachesGeneratedRequest() throws Excepti ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceUpdateRecord(anyString(), anyString(), anyString(), any(), any())) - .thenReturn(V1UpdateRecordResponse.builder().skyflowId("sky-id-1").build()); + when(mockRecords.updateRecord(anyString(), anyString(), anyString(), any(), any())) + .thenReturn(UpdateRecordResponse.builder().skyflowId("sky-id-1").build()); VaultController controller = newControllerWithMockApi(mockApi); @@ -508,17 +512,17 @@ public void testUpdate_everyBuilderValueReachesGeneratedRequest() throws Excepti ArgumentCaptor tableCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor idCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor bodyCaptor = - ArgumentCaptor.forClass(RecordServiceUpdateRecordBody.class); - Mockito.verify(mockRecords).recordServiceUpdateRecord( + ArgumentCaptor bodyCaptor = + ArgumentCaptor.forClass(UpdateRecordRequest.class); + Mockito.verify(mockRecords).updateRecord( eq(VAULT_ID), tableCaptor.capture(), idCaptor.capture(), bodyCaptor.capture(), any()); Assert.assertEquals("cards", tableCaptor.getValue()); Assert.assertEquals("skyflowId becomes the path id", "sky-id-1", idCaptor.getValue()); - RecordServiceUpdateRecordBody body = bodyCaptor.getValue(); + UpdateRecordRequest body = bodyCaptor.getValue(); Assert.assertTrue(body.getTokenization().get()); - Assert.assertEquals(V1Byot.ENABLE, body.getByot().get()); + Assert.assertEquals(UpdateRecordRequestByot.ENABLE, body.getByot().get()); Map fields = body.getRecord().get().getFields().get(); Assert.assertFalse("skyflowId must be stripped from fields", fields.containsKey("skyflowId")); @@ -535,8 +539,8 @@ public void testUpdate_deprecatedSkyflowIdKeyBecomesPathIdAndIsStripped() throws ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceUpdateRecord(anyString(), anyString(), anyString(), any(), any())) - .thenReturn(V1UpdateRecordResponse.builder().skyflowId("snake-id").build()); + when(mockRecords.updateRecord(anyString(), anyString(), anyString(), any(), any())) + .thenReturn(UpdateRecordResponse.builder().skyflowId("snake-id").build()); VaultController controller = newControllerWithMockApi(mockApi); @@ -547,9 +551,9 @@ public void testUpdate_deprecatedSkyflowIdKeyBecomesPathIdAndIsStripped() throws controller.update(UpdateRequest.builder().table("cards").data(data).build()); ArgumentCaptor idCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor bodyCaptor = - ArgumentCaptor.forClass(RecordServiceUpdateRecordBody.class); - Mockito.verify(mockRecords).recordServiceUpdateRecord( + ArgumentCaptor bodyCaptor = + ArgumentCaptor.forClass(UpdateRecordRequest.class); + Mockito.verify(mockRecords).updateRecord( anyString(), anyString(), idCaptor.capture(), bodyCaptor.capture(), any()); Assert.assertEquals("snake-id", idCaptor.getValue()); @@ -563,8 +567,8 @@ public void testUpdate_defaultsReachGeneratedRequest() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceUpdateRecord(anyString(), anyString(), anyString(), any(), any())) - .thenReturn(V1UpdateRecordResponse.builder().skyflowId("sky-id-1").build()); + when(mockRecords.updateRecord(anyString(), anyString(), anyString(), any(), any())) + .thenReturn(UpdateRecordResponse.builder().skyflowId("sky-id-1").build()); VaultController controller = newControllerWithMockApi(mockApi); @@ -574,13 +578,13 @@ public void testUpdate_defaultsReachGeneratedRequest() throws Exception { controller.update(UpdateRequest.builder().table("cards").data(data).build()); - ArgumentCaptor bodyCaptor = - ArgumentCaptor.forClass(RecordServiceUpdateRecordBody.class); - Mockito.verify(mockRecords).recordServiceUpdateRecord( + ArgumentCaptor bodyCaptor = + ArgumentCaptor.forClass(UpdateRecordRequest.class); + Mockito.verify(mockRecords).updateRecord( anyString(), anyString(), anyString(), bodyCaptor.capture(), any()); Assert.assertFalse("returnTokens defaults to false", bodyCaptor.getValue().getTokenization().get()); - Assert.assertEquals(V1Byot.DISABLE, bodyCaptor.getValue().getByot().get()); + Assert.assertEquals(UpdateRecordRequestByot.DISABLE, bodyCaptor.getValue().getByot().get()); Assert.assertFalse("no tokens supplied -> tokens absent", bodyCaptor.getValue().getRecord().get().getTokens().isPresent()); } @@ -594,8 +598,8 @@ public void testUpdate_mutatesCallersDataMap_knownGap() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceUpdateRecord(anyString(), anyString(), anyString(), any(), any())) - .thenReturn(V1UpdateRecordResponse.builder().skyflowId("sky-id-1").build()); + when(mockRecords.updateRecord(anyString(), anyString(), anyString(), any(), any())) + .thenReturn(UpdateRecordResponse.builder().skyflowId("sky-id-1").build()); VaultController controller = newControllerWithMockApi(mockApi); @@ -625,9 +629,9 @@ public void testUpdate_mutatesCallersDataMap_knownGap() throws Exception { private static VaultController mockGetController(RecordsClient mockRecords) throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceBulkGetRecord(anyString(), anyString(), any(), any())) - .thenReturn(V1BulkGetRecordResponse.builder() - .records(Collections.emptyList()) + when(mockRecords.getRecords(anyString(), anyString(), any(), any())) + .thenReturn(BulkGetRecordResponse.builder() + .records(Collections.emptyList()) .build()); return newControllerWithMockApi(mockApi); } @@ -651,21 +655,21 @@ public void testGet_idsFieldsRedactionAndPagingReachGeneratedRequest() throws Ex controller.get(request); ArgumentCaptor tableCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor requestCaptor = - ArgumentCaptor.forClass(RecordServiceBulkGetRecordRequest.class); - Mockito.verify(mockRecords).recordServiceBulkGetRecord( + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(GetRecordsRequest.class); + Mockito.verify(mockRecords).getRecords( eq(VAULT_ID), tableCaptor.capture(), requestCaptor.capture(), any()); Assert.assertEquals("cards", tableCaptor.getValue()); - RecordServiceBulkGetRecordRequest generated = requestCaptor.getValue(); + GetRecordsRequest generated = requestCaptor.getValue(); Assert.assertEquals("ids map to skyflowIds, order preserved", Arrays.asList("id-1", "id-2", "id-3"), generated.getSkyflowIds().get()); Assert.assertEquals(Arrays.asList("name", "card_number"), generated.getFields().get()); - Assert.assertEquals(RecordServiceBulkGetRecordRequestRedaction.PLAIN_TEXT, generated.getRedaction().get()); + Assert.assertEquals(GetRecordsRequestRedaction.PLAIN_TEXT, generated.getRedaction().get()); Assert.assertEquals("10", generated.getOffset().get()); Assert.assertEquals("25", generated.getLimit().get()); Assert.assertFalse("downloadUrl(false) must reach downloadURL", generated.getDownloadUrl().get()); - Assert.assertEquals(RecordServiceBulkGetRecordRequestOrderBy.DESCENDING, generated.getOrderBy().get()); + Assert.assertEquals(GetRecordsRequestOrderBy.DESCENDING, generated.getOrderBy().get()); Assert.assertFalse(generated.getColumnName().isPresent()); Assert.assertFalse(generated.getColumnValues().isPresent()); } @@ -684,16 +688,16 @@ public void testGet_columnNameAndColumnValuesReachGeneratedRequest() throws Exce controller.get(request); - ArgumentCaptor requestCaptor = - ArgumentCaptor.forClass(RecordServiceBulkGetRecordRequest.class); - Mockito.verify(mockRecords).recordServiceBulkGetRecord( + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(GetRecordsRequest.class); + Mockito.verify(mockRecords).getRecords( anyString(), anyString(), requestCaptor.capture(), any()); - RecordServiceBulkGetRecordRequest generated = requestCaptor.getValue(); + GetRecordsRequest generated = requestCaptor.getValue(); Assert.assertEquals("email", generated.getColumnName().get()); Assert.assertEquals(Arrays.asList("a@example.com", NON_ASCII_NAME, "value with spaces"), generated.getColumnValues().get()); - Assert.assertEquals(RecordServiceBulkGetRecordRequestRedaction.MASKED, generated.getRedaction().get()); + Assert.assertEquals(GetRecordsRequestRedaction.MASKED, generated.getRedaction().get()); Assert.assertFalse(generated.getSkyflowIds().isPresent()); } @@ -704,9 +708,9 @@ public void testGet_returnTokensMapsToTokenization() throws Exception { controller.get(GetRequest.builder().table("cards").ids(list("id-1")).returnTokens(true).build()); - ArgumentCaptor requestCaptor = - ArgumentCaptor.forClass(RecordServiceBulkGetRecordRequest.class); - Mockito.verify(mockRecords).recordServiceBulkGetRecord( + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(GetRecordsRequest.class); + Mockito.verify(mockRecords).getRecords( anyString(), anyString(), requestCaptor.capture(), any()); Assert.assertTrue(requestCaptor.getValue().getTokenization().get()); @@ -720,12 +724,12 @@ public void testGet_defaultOrderByAndDownloadUrlReachGeneratedRequest() throws E controller.get(GetRequest.builder().table("cards").ids(list("id-1")).build()); - ArgumentCaptor requestCaptor = - ArgumentCaptor.forClass(RecordServiceBulkGetRecordRequest.class); - Mockito.verify(mockRecords).recordServiceBulkGetRecord( + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(GetRecordsRequest.class); + Mockito.verify(mockRecords).getRecords( anyString(), anyString(), requestCaptor.capture(), any()); - Assert.assertEquals(RecordServiceBulkGetRecordRequestOrderBy.ASCENDING, + Assert.assertEquals(GetRecordsRequestOrderBy.ASCENDING, requestCaptor.getValue().getOrderBy().get()); Assert.assertTrue("downloadUrl defaults to true", requestCaptor.getValue().getDownloadUrl().get()); } @@ -738,11 +742,11 @@ public void testGet_orderByAcceptsAllThreeGeneratedEnumNames() throws Exception controller.get(GetRequest.builder().table("cards").ids(list("id-1")).orderBy(orderBy).build()); - ArgumentCaptor requestCaptor = - ArgumentCaptor.forClass(RecordServiceBulkGetRecordRequest.class); - Mockito.verify(mockRecords).recordServiceBulkGetRecord( + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(GetRecordsRequest.class); + Mockito.verify(mockRecords).getRecords( anyString(), anyString(), requestCaptor.capture(), any()); - Assert.assertEquals(RecordServiceBulkGetRecordRequestOrderBy.valueOf(orderBy), + Assert.assertEquals(GetRecordsRequestOrderBy.valueOf(orderBy), requestCaptor.getValue().getOrderBy().get()); } } @@ -766,7 +770,7 @@ public void testGet_orderByInvalidValueThrowsSkyflowException() throws Exception Assert.assertEquals(ErrorMessage.InvalidOrderBy.getMessage(), e.getMessage()); } Mockito.verify(mockRecords, Mockito.never()) - .recordServiceBulkGetRecord(anyString(), anyString(), any(), any()); + .getRecords(anyString(), anyString(), any(), any()); } } @@ -790,9 +794,9 @@ public void testGet_downloadUrlNullCoercesToTrueButReturnTokensNullDoesNot_known VaultController controller = mockGetController(mockRecords); controller.get(request); - ArgumentCaptor requestCaptor = - ArgumentCaptor.forClass(RecordServiceBulkGetRecordRequest.class); - Mockito.verify(mockRecords).recordServiceBulkGetRecord( + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(GetRecordsRequest.class); + Mockito.verify(mockRecords).getRecords( anyString(), anyString(), requestCaptor.capture(), any()); Assert.assertTrue("downloadURL=true is sent even though the user passed null", @@ -810,8 +814,8 @@ public void testDelete_tableAndIdsReachGeneratedRequest() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceBulkDeleteRecord(anyString(), anyString(), any(), any())) - .thenReturn(V1BulkDeleteRecordResponse.builder().build()); + when(mockRecords.deleteRecords(anyString(), anyString(), any(), any())) + .thenReturn(BulkDeleteRecordResponse.builder().build()); VaultController controller = newControllerWithMockApi(mockApi); controller.delete(DeleteRequest.builder() @@ -820,9 +824,9 @@ public void testDelete_tableAndIdsReachGeneratedRequest() throws Exception { .build()); ArgumentCaptor tableCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor bodyCaptor = - ArgumentCaptor.forClass(RecordServiceBulkDeleteRecordBody.class); - Mockito.verify(mockRecords).recordServiceBulkDeleteRecord( + ArgumentCaptor bodyCaptor = + ArgumentCaptor.forClass(BulkDeleteRecordRequest.class); + Mockito.verify(mockRecords).deleteRecords( eq(VAULT_ID), tableCaptor.capture(), bodyCaptor.capture(), any()); Assert.assertEquals("cards", tableCaptor.getValue()); @@ -839,8 +843,8 @@ public void testQuery_queryStringReachesGeneratedBodyVerbatim() throws Exception ApiClient mockApi = Mockito.mock(ApiClient.class); QueryClient mockQuery = Mockito.mock(QueryClient.class); when(mockApi.query()).thenReturn(mockQuery); - when(mockQuery.queryServiceExecuteQuery(anyString(), any(), any())) - .thenReturn(V1GetQueryResponse.builder().build()); + when(mockQuery.executeQuery(anyString(), any(), any())) + .thenReturn(GetQueryResponse.builder().build()); VaultController controller = newControllerWithMockApi(mockApi); @@ -848,12 +852,12 @@ public void testQuery_queryStringReachesGeneratedBodyVerbatim() throws Exception + "WHERE name = 'Smith''s' AND city = '" + NON_ASCII_CITY + "'\nLIMIT 10"; controller.query(QueryRequest.builder().query(sql).build()); - ArgumentCaptor bodyCaptor = - ArgumentCaptor.forClass(QueryServiceExecuteQueryBody.class); - Mockito.verify(mockQuery).queryServiceExecuteQuery(eq(VAULT_ID), bodyCaptor.capture(), any()); + ArgumentCaptor bodyCaptor = + ArgumentCaptor.forClass(GetQueryRequest.class); + Mockito.verify(mockQuery).executeQuery(eq(VAULT_ID), bodyCaptor.capture(), any()); Assert.assertEquals("query with quotes and newlines must be sent unchanged", - sql, bodyCaptor.getValue().getQuery().get()); + sql, bodyCaptor.getValue().getQuery()); } @Test @@ -861,16 +865,16 @@ public void testQuery_simpleQueryReachesGeneratedBody() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); QueryClient mockQuery = Mockito.mock(QueryClient.class); when(mockApi.query()).thenReturn(mockQuery); - when(mockQuery.queryServiceExecuteQuery(anyString(), any(), any())) - .thenReturn(V1GetQueryResponse.builder().build()); + when(mockQuery.executeQuery(anyString(), any(), any())) + .thenReturn(GetQueryResponse.builder().build()); VaultController controller = newControllerWithMockApi(mockApi); controller.query(QueryRequest.builder().query("SELECT * FROM cards LIMIT 1").build()); - ArgumentCaptor bodyCaptor = - ArgumentCaptor.forClass(QueryServiceExecuteQueryBody.class); - Mockito.verify(mockQuery).queryServiceExecuteQuery(anyString(), bodyCaptor.capture(), any()); - Assert.assertEquals("SELECT * FROM cards LIMIT 1", bodyCaptor.getValue().getQuery().get()); + ArgumentCaptor bodyCaptor = + ArgumentCaptor.forClass(GetQueryRequest.class); + Mockito.verify(mockQuery).executeQuery(anyString(), bodyCaptor.capture(), any()); + Assert.assertEquals("SELECT * FROM cards LIMIT 1", bodyCaptor.getValue().getQuery()); } // ================================================================== @@ -886,10 +890,10 @@ public void testTokenize_columnValuesReachPayloadInOrder() { ColumnValue.builder().value(NON_ASCII_NAME).columnGroup("cg_names").build(), ColumnValue.builder().value("value with spaces").columnGroup("cg_misc").build()); - V1TokenizePayload payload = client.getTokenizePayload( + TokenizePayload payload = client.getTokenizePayload( TokenizeRequest.builder().values(columnValues).build()); - List parameters = payload.getTokenizationParameters().get(); + List parameters = payload.getTokenizationParameters(); Assert.assertEquals(3, parameters.size()); Assert.assertEquals("4111111111111111", parameters.get(0).getValue().get()); Assert.assertEquals("cg_cards", parameters.get(0).getColumnGroup().get()); @@ -905,17 +909,17 @@ public void testTokenize_payloadReachesGeneratedApiCall() throws Exception { com.skyflow.generated.rest.resources.tokens.TokensClient mockTokens = Mockito.mock(com.skyflow.generated.rest.resources.tokens.TokensClient.class); when(mockApi.tokens()).thenReturn(mockTokens); - when(mockTokens.recordServiceTokenize(anyString(), any(), any())) - .thenReturn(V1TokenizeResponse.builder().build()); + when(mockTokens.tokenize(anyString(), any(), any())) + .thenReturn(com.skyflow.generated.rest.types.TokenizeResponse.builder().build()); VaultController controller = newControllerWithMockApi(mockApi); controller.tokenize(TokenizeRequest.builder().values(Collections.singletonList( ColumnValue.builder().value(NON_ASCII_NAME).columnGroup("cg_names").build())).build()); - ArgumentCaptor payloadCaptor = ArgumentCaptor.forClass(V1TokenizePayload.class); - Mockito.verify(mockTokens).recordServiceTokenize(eq(VAULT_ID), payloadCaptor.capture(), any()); + ArgumentCaptor payloadCaptor = ArgumentCaptor.forClass(TokenizePayload.class); + Mockito.verify(mockTokens).tokenize(eq(VAULT_ID), payloadCaptor.capture(), any()); - V1TokenizeRecordRequest parameter = payloadCaptor.getValue().getTokenizationParameters().get().get(0); + TokenizeRecordRequest parameter = payloadCaptor.getValue().getTokenizationParameters().get(0); Assert.assertEquals(NON_ASCII_NAME, parameter.getValue().get()); Assert.assertEquals("cg_names", parameter.getColumnGroup().get()); } @@ -934,20 +938,20 @@ public void testDetokenize_eachTokenKeepsItsOwnRedactionType() { new DetokenizeData("tok-masked", RedactionType.MASKED), new DetokenizeData("tok-redacted", RedactionType.REDACTED))); - V1DetokenizePayload payload = client.getDetokenizePayload( + DetokenizePayload payload = client.getDetokenizePayload( DetokenizeRequest.builder().detokenizeData(detokenizeData).build()); - List parameters = payload.getDetokenizationParameters().get(); + List parameters = payload.getDetokenizationParameters(); Assert.assertEquals(4, parameters.size()); - Assert.assertEquals("tok-default", parameters.get(0).getToken().get()); - Assert.assertEquals(RedactionEnumRedaction.DEFAULT, parameters.get(0).getRedaction().get()); - Assert.assertEquals("tok-plain", parameters.get(1).getToken().get()); - Assert.assertEquals(RedactionEnumRedaction.PLAIN_TEXT, parameters.get(1).getRedaction().get()); - Assert.assertEquals("tok-masked", parameters.get(2).getToken().get()); - Assert.assertEquals(RedactionEnumRedaction.MASKED, parameters.get(2).getRedaction().get()); - Assert.assertEquals("tok-redacted", parameters.get(3).getToken().get()); - Assert.assertEquals(RedactionEnumRedaction.REDACTED, parameters.get(3).getRedaction().get()); + Assert.assertEquals("tok-default", parameters.get(0).getToken()); + Assert.assertEquals(DetokenizeRecordRequestRedaction.DEFAULT, parameters.get(0).getRedaction().get()); + Assert.assertEquals("tok-plain", parameters.get(1).getToken()); + Assert.assertEquals(DetokenizeRecordRequestRedaction.PLAIN_TEXT, parameters.get(1).getRedaction().get()); + Assert.assertEquals("tok-masked", parameters.get(2).getToken()); + Assert.assertEquals(DetokenizeRecordRequestRedaction.MASKED, parameters.get(2).getRedaction().get()); + Assert.assertEquals("tok-redacted", parameters.get(3).getToken()); + Assert.assertEquals(DetokenizeRecordRequestRedaction.REDACTED, parameters.get(3).getRedaction().get()); } @Test @@ -957,12 +961,12 @@ public void testDetokenize_tokenWithoutRedactionDefaultsToDefault() { new DetokenizeData("tok-a"), new DetokenizeData("tok-b", null))); - V1DetokenizePayload payload = client.getDetokenizePayload( + DetokenizePayload payload = client.getDetokenizePayload( DetokenizeRequest.builder().detokenizeData(detokenizeData).build()); - List parameters = payload.getDetokenizationParameters().get(); - Assert.assertEquals(RedactionEnumRedaction.DEFAULT, parameters.get(0).getRedaction().get()); - Assert.assertEquals(RedactionEnumRedaction.DEFAULT, parameters.get(1).getRedaction().get()); + List parameters = payload.getDetokenizationParameters(); + Assert.assertEquals(DetokenizeRecordRequestRedaction.DEFAULT, parameters.get(0).getRedaction().get()); + Assert.assertEquals(DetokenizeRecordRequestRedaction.DEFAULT, parameters.get(1).getRedaction().get()); } @Test @@ -971,7 +975,7 @@ public void testDetokenize_continueOnErrorAndDownloadUrlReachPayload() { ArrayList detokenizeData = new ArrayList<>(Collections.singletonList(new DetokenizeData("tok-a"))); - V1DetokenizePayload payload = client.getDetokenizePayload(DetokenizeRequest.builder() + DetokenizePayload payload = client.getDetokenizePayload(DetokenizeRequest.builder() .detokenizeData(detokenizeData) .continueOnError(true) .downloadUrl(true) @@ -979,7 +983,7 @@ public void testDetokenize_continueOnErrorAndDownloadUrlReachPayload() { Assert.assertTrue(payload.getContinueOnError().get()); Assert.assertTrue(payload.getDownloadUrl().get()); - V1DetokenizePayload defaults = client.getDetokenizePayload(DetokenizeRequest.builder() + DetokenizePayload defaults = client.getDetokenizePayload(DetokenizeRequest.builder() .detokenizeData(detokenizeData) .build()); Assert.assertFalse("continueOnError defaults to false", defaults.getContinueOnError().get()); @@ -994,12 +998,12 @@ public void testDetokenize_tokenOrderIsPreserved() { detokenizeData.add(new DetokenizeData("tok-" + i, RedactionType.MASKED)); } - List parameters = client.getDetokenizePayload( + List parameters = client.getDetokenizePayload( DetokenizeRequest.builder().detokenizeData(detokenizeData).build()) - .getDetokenizationParameters().get(); + .getDetokenizationParameters(); for (int i = 0; i < 5; i++) { - Assert.assertEquals("tok-" + i, parameters.get(i).getToken().get()); + Assert.assertEquals("tok-" + i, parameters.get(i).getToken()); } } @@ -1007,11 +1011,11 @@ public void testDetokenize_tokenOrderIsPreserved() { // uploadFile // ================================================================== - private static VaultController mockUploadController(RecordsClient mockRecords) throws Exception { + private static VaultController mockUploadController(FilesClient mockFiles) throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); - when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.uploadFileV2(anyString(), any(File.class), any(), any())) - .thenReturn(UploadFileV2Response.builder().build()); + when(mockApi.files()).thenReturn(mockFiles); + when(mockFiles.uploadFileV2(anyString(), any(File.class), any(), any())) + .thenReturn(UploadFileResponseV2.builder().build()); return newControllerWithMockApi(mockApi); } @@ -1021,8 +1025,8 @@ public void testUploadFile_metadataFieldsAndFilePathReachGeneratedRequest() thro tempFile.deleteOnExit(); Files.write(tempFile.toPath(), "hello".getBytes("UTF-8")); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - VaultController controller = mockUploadController(mockRecords); + FilesClient mockFiles = Mockito.mock(FilesClient.class); + VaultController controller = mockUploadController(mockFiles); controller.uploadFile(FileUploadRequest.builder() .table("cards") @@ -1032,11 +1036,11 @@ public void testUploadFile_metadataFieldsAndFilePathReachGeneratedRequest() thro .build()); ArgumentCaptor fileCaptor = ArgumentCaptor.forClass(File.class); - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(UploadFileV2Request.class); - Mockito.verify(mockRecords).uploadFileV2( + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(UploadFileRequestV2.class); + Mockito.verify(mockFiles).uploadFileV2( eq(VAULT_ID), fileCaptor.capture(), requestCaptor.capture(), any()); - UploadFileV2Request generated = requestCaptor.getValue(); + UploadFileRequestV2 generated = requestCaptor.getValue(); Assert.assertEquals("table maps to tableName", "cards", generated.getTableName()); Assert.assertEquals("file_column", generated.getColumnName()); Assert.assertEquals("sky-id-9", generated.getSkyflowId().get()); @@ -1054,8 +1058,8 @@ public void testUploadFile_base64AndFileNameProduceMatchingFile() throws Excepti byte[] payload = "café ☕".getBytes("UTF-8"); String base64 = Base64.getEncoder().encodeToString(payload); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - VaultController controller = mockUploadController(mockRecords); + FilesClient mockFiles = Mockito.mock(FilesClient.class); + VaultController controller = mockUploadController(mockFiles); controller.uploadFile(FileUploadRequest.builder() .table("cards") @@ -1066,8 +1070,8 @@ public void testUploadFile_base64AndFileNameProduceMatchingFile() throws Excepti .build()); ArgumentCaptor fileCaptor = ArgumentCaptor.forClass(File.class); - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(UploadFileV2Request.class); - Mockito.verify(mockRecords).uploadFileV2( + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(UploadFileRequestV2.class); + Mockito.verify(mockFiles).uploadFileV2( anyString(), fileCaptor.capture(), requestCaptor.capture(), any()); Assert.assertEquals(target.getAbsolutePath(), fileCaptor.getValue().getPath()); @@ -1082,8 +1086,8 @@ public void testUploadFile_fileObjectIsPassedThroughUnchanged() throws Exception tempFile.deleteOnExit(); Files.write(tempFile.toPath(), new byte[]{1, 2, 3}); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - VaultController controller = mockUploadController(mockRecords); + FilesClient mockFiles = Mockito.mock(FilesClient.class); + VaultController controller = mockUploadController(mockFiles); controller.uploadFile(FileUploadRequest.builder() .table("cards") @@ -1092,8 +1096,8 @@ public void testUploadFile_fileObjectIsPassedThroughUnchanged() throws Exception .build()); ArgumentCaptor fileCaptor = ArgumentCaptor.forClass(File.class); - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(UploadFileV2Request.class); - Mockito.verify(mockRecords).uploadFileV2( + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(UploadFileRequestV2.class); + Mockito.verify(mockFiles).uploadFileV2( anyString(), fileCaptor.capture(), requestCaptor.capture(), any()); Assert.assertSame("the caller's File instance must be forwarded", tempFile, fileCaptor.getValue()); @@ -1110,8 +1114,8 @@ public void testUploadFile_filePathTakesPrecedenceOverOtherSources() throws Exce objectFile.deleteOnExit(); Files.write(objectFile.toPath(), "from-object".getBytes("UTF-8")); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - VaultController controller = mockUploadController(mockRecords); + FilesClient mockFiles = Mockito.mock(FilesClient.class); + VaultController controller = mockUploadController(mockFiles); controller.uploadFile(FileUploadRequest.builder() .table("cards") @@ -1121,7 +1125,7 @@ public void testUploadFile_filePathTakesPrecedenceOverOtherSources() throws Exce .build()); ArgumentCaptor fileCaptor = ArgumentCaptor.forClass(File.class); - Mockito.verify(mockRecords).uploadFileV2(anyString(), fileCaptor.capture(), any(), any()); + Mockito.verify(mockFiles).uploadFileV2(anyString(), fileCaptor.capture(), any(), any()); Assert.assertEquals(pathFile.getAbsolutePath(), fileCaptor.getValue().getPath()); } diff --git a/skyvault/src/test/java/com/skyflow/VaultClientTests.java b/skyvault/src/test/java/com/skyflow/VaultClientTests.java index 312e2892..75339585 100644 --- a/skyvault/src/test/java/com/skyflow/VaultClientTests.java +++ b/skyvault/src/test/java/com/skyflow/VaultClientTests.java @@ -7,26 +7,12 @@ import com.skyflow.enums.*; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.resources.files.requests.*; -import com.skyflow.generated.rest.resources.files.FilesClient; import com.skyflow.generated.rest.types.*; import com.skyflow.generated.rest.resources.query.QueryClient; import com.skyflow.generated.rest.resources.records.RecordsClient; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; -import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; -import com.skyflow.generated.rest.resources.strings.StringsClient; -import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; -import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; import com.skyflow.generated.rest.resources.tokens.TokensClient; -import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; -import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; -import com.skyflow.vault.detect.*; -import com.skyflow.vault.detect.DeidentifyFileRequest; -import com.skyflow.vault.detect.DeidentifyTextRequest; -import com.skyflow.vault.detect.Transformations; import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; @@ -52,6 +38,12 @@ import java.util.*; import java.util.Arrays; import java.util.Collections; +import com.skyflow.generated.rest.resources.tokens.requests.TokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.DetokenizePayload; +import com.skyflow.generated.rest.resources.records.types.InsertRecordRequestByot; +import com.skyflow.generated.rest.resources.records.requests.UpdateRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.InsertRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.BatchOperationRequest; public class VaultClientTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; @@ -112,28 +104,6 @@ public void testVaultClientGetRecordsAPI() { } } - @Test - public void testVaultClientDetectAPI() { - try { - FilesClient filesClient = vaultClient.getDetectFileAPi(); - Assert.assertNotNull(filesClient); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN + e.getMessage()); - } - } - - @Test - public void testVaultClientDetectTextAPI() { - try { - StringsClient stringsClient = vaultClient.getDetectTextApi(); - Assert.assertNotNull(stringsClient); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN + e.getMessage()); - } - } - @Test public void testVaultClientGetTokensAPI() { try { @@ -179,10 +149,10 @@ public void testGetDetokenizePayload() { .downloadURL(true) .continueOnError(false) .build(); - V1DetokenizePayload payload = vaultClient.getDetokenizePayload(detokenizeRequest); + DetokenizePayload payload = vaultClient.getDetokenizePayload(detokenizeRequest); Assert.assertFalse(payload.getContinueOnError().get()); Assert.assertTrue(payload.getDownloadUrl().get()); - Assert.assertEquals(2, payload.getDetokenizationParameters().get().size()); + Assert.assertEquals(2, payload.getDetokenizationParameters().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -208,17 +178,17 @@ public void testGetBulkInsertRequestBody() { .tokenMode(TokenMode.ENABLE) .returnTokens(true) .build(); - RecordServiceInsertRecordBody body1 = vaultClient.getBulkInsertRequestBody(insertRequest1); + InsertRecordRequest body1 = vaultClient.getBulkInsertRequestBody(insertRequest1); Assert.assertTrue(body1.getTokenization().get()); - Assert.assertEquals(V1Byot.ENABLE, body1.getByot().get()); - Assert.assertEquals(2, body1.getRecords().get().size()); + Assert.assertEquals(InsertRecordRequestByot.ENABLE, body1.getByot().get()); + Assert.assertEquals(2, body1.getRecords().size()); InsertRequest insertRequest2 = InsertRequest.builder() .table(table) .values(insertValues) .build(); - RecordServiceInsertRecordBody body2 = vaultClient.getBulkInsertRequestBody(insertRequest2); - Assert.assertEquals(2, body2.getRecords().get().size()); + InsertRecordRequest body2 = vaultClient.getBulkInsertRequestBody(insertRequest2); + Assert.assertEquals(2, body2.getRecords().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -244,13 +214,13 @@ public void testGetBatchInsertRequestBody() { .tokenMode(TokenMode.ENABLE) .returnTokens(false) .build(); - RecordServiceBatchOperationBody body1 = vaultClient.getBatchInsertRequestBody(insertRequest1); + BatchOperationRequest body1 = vaultClient.getBatchInsertRequestBody(insertRequest1); Assert.assertTrue(body1.getContinueOnError().get()); - Assert.assertEquals(2, body1.getRecords().get().size()); + Assert.assertEquals(2, body1.getRecords().size()); InsertRequest insertRequest2 = InsertRequest.builder().table(table).values(insertValues).build(); - RecordServiceBatchOperationBody body2 = vaultClient.getBatchInsertRequestBody(insertRequest2); - Assert.assertEquals(2, body2.getRecords().get().size()); + BatchOperationRequest body2 = vaultClient.getBatchInsertRequestBody(insertRequest2); + Assert.assertEquals(2, body2.getRecords().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -270,7 +240,7 @@ public void testGetUpdateRequestBodyWithTokens() { .tokens(tokenMap) .returnTokens(true) .build(); - RecordServiceUpdateRecordBody body = vaultClient.getUpdateRequestBody(updateRequest); + UpdateRecordRequest body = vaultClient.getUpdateRequestBody(updateRequest); Assert.assertTrue(body.getTokenization().get()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -290,7 +260,7 @@ public void testGetUpdateRequestBodyWithoutTokens() { .data(valueMap) .returnTokens(false) .build(); - RecordServiceUpdateRecordBody body = vaultClient.getUpdateRequestBody(updateRequest); + UpdateRecordRequest body = vaultClient.getUpdateRequestBody(updateRequest); Assert.assertFalse(body.getTokenization().get()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -304,8 +274,8 @@ public void testGetTokenizePayload() { List columnValues = new ArrayList<>(); columnValues.add(columnValue); TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); - V1TokenizePayload payload = vaultClient.getTokenizePayload(tokenizeRequest); - Assert.assertEquals(1, payload.getTokenizationParameters().get().size()); + TokenizePayload payload = vaultClient.getTokenizePayload(tokenizeRequest); + Assert.assertEquals(1, payload.getTokenizationParameters().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -369,566 +339,8 @@ public void testSetBearerTokenWithEnvCredentials() { } } - @Test - public void testGetDeIdentifyTextResponse() { - List entities = new ArrayList<>(); - Locations location = Locations.builder() - .startIndex(2) - .endIndex(10) - .startIndexProcessed(3) - .endIndexProcessed(8) - .build(); - - StringResponseEntities detectedEntity = StringResponseEntities.builder() - .token("token123") - .value("value123") - .location(location) - .build(); - entities.add(detectedEntity); - - DeidentifyStringResponse response = DeidentifyStringResponse.builder() - .processedText("processed text") - .wordCount(2) - .characterCount(13) - .entities(entities) - .build(); - - - DeidentifyTextResponse result = vaultClient.getDeIdentifyTextResponse(response); - - Assert.assertNotNull(result); - Assert.assertEquals("processed text", result.getProcessedText()); - Assert.assertEquals(2, result.getWordCount()); - Assert.assertEquals(13, result.getCharCount()); - Assert.assertNotNull(result.getEntities()); - Assert.assertEquals(1, result.getEntities().size()); - Assert.assertEquals("token123", result.getEntities().get(0).getToken()); - Assert.assertEquals("value123", result.getEntities().get(0).getValue()); - Assert.assertEquals(2, result.getEntities().get(0).getTextIndex().getStart()); - Assert.assertEquals(10, result.getEntities().get(0).getTextIndex().getEnd()); - Assert.assertEquals(3, result.getEntities().get(0).getProcessedIndex().getStart()); - Assert.assertEquals(8, result.getEntities().get(0).getProcessedIndex().getEnd()); - } - - @Test - public void testGetDeidentifyStringRequest() { - - List detectEntitiesList = new ArrayList<>(); - detectEntitiesList.add(DetectEntities.NAME); - - List vaultTokenList = new ArrayList<>(); - vaultTokenList.add(DetectEntities.SSN); - - - List entityOnlyList = new ArrayList<>(); - entityOnlyList.add(DetectEntities.DOB); - - List entityUniqueCounterList = new ArrayList<>(); - entityUniqueCounterList.add(DetectEntities.NAME); - - - List restrictRegexList = new ArrayList<>(); - restrictRegexList.add("([0-9]{3}-[0-9]{2}-[0-9]{4})"); - - TokenFormat tokenFormat = TokenFormat.builder() - .vaultToken(vaultTokenList) - .entityOnly(entityOnlyList) - .entityUniqueCounter(entityUniqueCounterList) - .build(); - - - List detectEntitiesTransformationList = new ArrayList<>(); - detectEntitiesTransformationList.add(DetectEntities.DOB); - detectEntitiesTransformationList.add(DetectEntities.DATE); - - DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); - Transformations transformations = new Transformations(dateTransformation); - - - DeidentifyTextRequest req = DeidentifyTextRequest.builder() - .text("Sensitive data to deidentify, like Name: Joy SSN 123-45-6789 and DOB 01-01-2000.") - .entities(detectEntitiesList) - .restrictRegexList(restrictRegexList) - .tokenFormat(tokenFormat) - .transformations(transformations) - .build(); - - } - - @Test - public void testDeidentifyFileRequestBuilderAndGetters() { - File file = new File("testfile.txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - DetectEntities entity = DetectEntities.NAME; - String allowRegex = "^[A-Za-z]+$"; - String restrictRegex = "\\d+"; - TokenFormat tokenFormat = TokenFormat.builder().vaultToken(Collections.singletonList(entity)).build(); - Boolean outputProcessedImage = true; - Boolean outputOcrText = true; - MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; - Double pixelDensity = 300.0; - Double maxResolution = 1024.0; - Boolean outputProcessedAudio = false; - DetectOutputTranscriptions outputTranscription = DetectOutputTranscriptions.TRANSCRIPTION; - AudioBleep bleep = AudioBleep.builder().gain(20.0).build(); - String outputDirectory = "/tmp"; - Integer waitTime = 10; - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(Arrays.asList(entity)) - .allowRegexList(Collections.singletonList(allowRegex)) - .restrictRegexList(Collections.singletonList(restrictRegex)) - .tokenFormat(tokenFormat) - .outputProcessedImage(outputProcessedImage) - .outputOcrText(outputOcrText) - .maskingMethod(maskingMethod) - .pixelDensity(pixelDensity) - .maxResolution(maxResolution) - .outputProcessedAudio(outputProcessedAudio) - .outputTranscription(outputTranscription) - .bleep(bleep) - .outputDirectory(outputDirectory) - .waitTime(waitTime) - .build(); - - Assert.assertEquals(file, request.getFileInput().getFile()); - Assert.assertEquals(1, request.getEntities().size()); - Assert.assertEquals(allowRegex, request.getAllowRegexList().get(0)); - Assert.assertEquals(restrictRegex, request.getRestrictRegexList().get(0)); - Assert.assertEquals(tokenFormat, request.getTokenFormat()); - Assert.assertEquals(outputProcessedImage, request.getOutputProcessedImage()); - Assert.assertEquals(outputOcrText, request.getOutputOcrText()); - Assert.assertEquals(maskingMethod, request.getMaskingMethod()); - Assert.assertEquals(pixelDensity, request.getPixelDensity()); - Assert.assertEquals(maxResolution, request.getMaxResolution()); - Assert.assertEquals(outputProcessedAudio, request.getOutputProcessedAudio()); - Assert.assertEquals(outputTranscription, request.getOutputTranscription()); - Assert.assertEquals(bleep, request.getBleep()); - Assert.assertEquals(outputDirectory, request.getOutputDirectory()); - Assert.assertEquals(waitTime, request.getWaitTime()); - } - - @Test - public void testDeidentifyFileRequestBuilderDefaults() { - DeidentifyFileRequest request = DeidentifyFileRequest.builder().build(); - Assert.assertNull(request.getEntities()); - Assert.assertNull(request.getAllowRegexList()); - Assert.assertNull(request.getRestrictRegexList()); - Assert.assertNull(request.getTokenFormat()); - Assert.assertNull(request.getTransformations()); - Assert.assertEquals(false, request.getOutputProcessedImage()); - Assert.assertEquals(false, request.getOutputOcrText()); - Assert.assertNull(request.getMaskingMethod()); - Assert.assertNull(request.getPixelDensity()); - Assert.assertNull(request.getMaxResolution()); - Assert.assertEquals(false, request.getOutputProcessedAudio()); - Assert.assertNull(request.getOutputTranscription()); - Assert.assertNull(request.getBleep()); - Assert.assertNull(request.getOutputDirectory()); - Assert.assertNull(request.getWaitTime()); - } - - @Test - public void testGetDeidentifyImageRequest() { - File file = new File("test.jpg"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .outputProcessedImage(true) - .outputOcrText(true) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - String format = "jpg"; - - DeidentifyFileImageRequestDeidentifyImage imageRequest = vaultClient.getDeidentifyImageRequest(request, vaultId, base64Content, format); - - Assert.assertEquals(vaultId, imageRequest.getVaultId()); - Assert.assertEquals(base64Content, imageRequest.getFile().getBase64()); - Assert.assertEquals(format.toUpperCase(), imageRequest.getFile().getDataFormat().name()); - } - - @Test - public void testGetDeidentifyPresentationRequest() { - File file = new File("test.pptx"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - String format = "pptx"; - - DeidentifyFileRequestDeidentifyPresentation presRequest = vaultClient.getDeidentifyPresentationRequest(request, vaultId, base64Content, format); - - Assert.assertEquals(vaultId, presRequest.getVaultId()); - Assert.assertEquals(base64Content, presRequest.getFile().getBase64()); - Assert.assertEquals(format.toUpperCase(), presRequest.getFile().getDataFormat().name()); - } - - @Test - public void testGetDeidentifySpreadsheetRequest() { - File file = new File("test.csv"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - String format = "csv"; - - DeidentifyFileRequestDeidentifySpreadsheet spreadsheetRequest = vaultClient.getDeidentifySpreadsheetRequest(request, vaultId, base64Content, format); - - Assert.assertEquals(vaultId, spreadsheetRequest.getVaultId()); - Assert.assertEquals(base64Content, spreadsheetRequest.getFile().getBase64()); - Assert.assertEquals(format.toUpperCase(), spreadsheetRequest.getFile().getDataFormat().name()); - } - - @Test - public void testGetDeidentifyStructuredTextRequest() { - File file = new File("test.json"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - String format = "json"; - - DeidentifyFileRequestDeidentifyStructuredText structuredTextRequest = vaultClient.getDeidentifyStructuredTextRequest(request, vaultId, base64Content, format); - - Assert.assertEquals(vaultId, structuredTextRequest.getVaultId()); - Assert.assertEquals(base64Content, structuredTextRequest.getFile().getBase64()); - Assert.assertEquals(format.toUpperCase(), structuredTextRequest.getFile().getDataFormat().name()); - } - - @Test - public void testGetDeidentifyDocumentRequest() { - File file = new File("test.docx"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - String format = "docx"; - - DeidentifyFileRequestDeidentifyDocument documentRequest = vaultClient.getDeidentifyDocumentRequest(request, vaultId, base64Content, format); - - Assert.assertEquals(vaultId, documentRequest.getVaultId()); - Assert.assertEquals(base64Content, documentRequest.getFile().getBase64()); - Assert.assertEquals(format.toUpperCase(), documentRequest.getFile().getDataFormat().name()); - } - - @Test - public void testGetDeidentifyPdfRequest() { - File file = new File("test.pdf"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .pixelDensity(200) - .maxResolution(300) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - - DeidentifyFileDocumentPdfRequestDeidentifyPdf pdfRequest = vaultClient.getDeidentifyPdfRequest(request, vaultId, base64Content); - - Assert.assertEquals(vaultId, pdfRequest.getVaultId()); - Assert.assertEquals(base64Content, pdfRequest.getFile().getBase64()); - } - - @Test - public void testGetDeidentifyAudioRequest() throws SkyflowException { - File file = new File("test.mp3"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - AudioBleep bleep = AudioBleep.builder().frequency(1000.0).gain(10.0).startPadding(1.0).stopPadding(1.0).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .bleep(bleep) - .outputProcessedAudio(true) - .outputTranscription(DetectOutputTranscriptions.TRANSCRIPTION) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - String dataFormat = "mp3"; - - DeidentifyFileAudioRequestDeidentifyAudio audioRequest = vaultClient.getDeidentifyAudioRequest(request, vaultId, base64Content, dataFormat); - - Assert.assertEquals(vaultId, audioRequest.getVaultId()); - Assert.assertEquals(base64Content, audioRequest.getFile().getBase64()); - Assert.assertEquals(dataFormat, audioRequest.getFile().getDataFormat().toString()); - } - - @Test - public void testGetDeidentifyTextFileRequest() { - File file = new File("test.txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - - DeidentifyFileRequestDeidentifyText textRequest = - vaultClient.getDeidentifyTextFileRequest(request, vaultId, base64Content); - - Assert.assertEquals(vaultId, textRequest.getVaultId()); - Assert.assertEquals(base64Content, textRequest.getFile().getBase64()); - } - - @Test - public void testGetDeidentifyStringRequest_AllTokenFormatFields() throws Exception { - List entities = Arrays.asList(DetectEntities.DOB); - List vaultToken = Collections.singletonList(DetectEntities.SSN); - List entityOnly = Collections.singletonList(DetectEntities.DOB); - List entityUniqueCounter = Collections.singletonList(DetectEntities.NAME); - - TokenFormat tokenFormat = TokenFormat.builder() - .vaultToken(vaultToken) - .entityOnly(entityOnly) - .entityUniqueCounter(entityUniqueCounter) - .build(); - - List allowRegex = Collections.singletonList("a.*"); - List restrictRegex = Collections.singletonList("b.*"); - - DateTransformation dateTransformation = new DateTransformation(10, 5, entities); - Transformations transformations = new Transformations(dateTransformation); - - DeidentifyTextRequest req = DeidentifyTextRequest.builder() - .text("Sensitive data") - .entities(entities) - .allowRegexList(allowRegex) - .restrictRegexList(restrictRegex) - .tokenFormat(tokenFormat) - .transformations(transformations) - .build(); - - DeidentifyStringRequest result = vaultClient.getDeidentifyStringRequest(req, "vaultId"); - Assert.assertNotNull(result); - Assert.assertEquals("vaultId", result.getVaultId()); - Assert.assertEquals("Sensitive data", result.getText()); - Assert.assertTrue(result.getAllowRegex().isPresent()); - Assert.assertTrue(result.getRestrictRegex().isPresent()); - Assert.assertTrue(result.getTransformations().isPresent()); - } - - @Test - public void testGetDeidentifyStringRequest_NullTokenFormatAndEntities() throws Exception { - DeidentifyTextRequest req = DeidentifyTextRequest.builder() - .text("No entities or tokenFormat") - .build(); - - DeidentifyStringRequest result = vaultClient.getDeidentifyStringRequest(req, "vaultId"); - Assert.assertNotNull(result); - Assert.assertEquals("vaultId", result.getVaultId()); - Assert.assertEquals("No entities or tokenFormat", result.getText()); - } - - @Test - public void testGetReidentifyStringRequest_AllFields() throws Exception { - List masked = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); - List plaintext = Collections.singletonList(DetectEntities.SSN); - List redacted = Collections.singletonList(DetectEntities.DATE); - - ReidentifyTextRequest req = ReidentifyTextRequest.builder() - .text("Sensitive data") - .maskedEntities(masked) - .plainTextEntities(plaintext) - .redactedEntities(redacted) - .build(); - - ReidentifyStringRequest result = vaultClient.getReidentifyStringRequest(req, "vaultId"); - Assert.assertNotNull(result); - Assert.assertEquals("vaultId", result.getVaultId().get()); - Assert.assertEquals("Sensitive data", result.getText().get()); - Assert.assertNotNull(result.getFormat()); - } - - @Test - public void testGetReidentifyStringRequest_NullFields() throws Exception { - ReidentifyTextRequest req = ReidentifyTextRequest.builder() - .text("No entities") - .build(); - - ReidentifyStringRequest result = vaultClient.getReidentifyStringRequest(req, "vaultId"); - Assert.assertNotNull(result); - Assert.assertEquals("vaultId", result.getVaultId().get()); - Assert.assertEquals("No entities", result.getText().get()); - Assert.assertNotNull(result.getFormat()); - } - - @Test - public void testGetTransformations_NullInput() throws Exception { - // Should return null if input is null - java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); - method.setAccessible(true); - Object result = method.invoke(vaultClient, new Object[]{null}); - Assert.assertNull(result); - } - - @Test - public void testGetTransformations_NullShiftDates() throws Exception { - Transformations transformations = new Transformations(null); - java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); - method.setAccessible(true); - Object result = method.invoke(vaultClient, transformations); - Assert.assertNull(result); - } - - @Test - public void testGetTransformations_EmptyEntities() throws Exception { - DateTransformation dateTransformation = new DateTransformation(10, 5, new ArrayList<>()); - Transformations transformations = new Transformations(dateTransformation); - java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); - method.setAccessible(true); - Object result = method.invoke(vaultClient, transformations); - Assert.assertNotNull(result); - // Should have empty entityTypes list - com.skyflow.generated.rest.types.Transformations restTransform = (com.skyflow.generated.rest.types.Transformations) result; - Assert.assertTrue(restTransform.getShiftDates().get().getEntityTypes().get().isEmpty()); - } - - @Test - public void testGetTransformations_WithEntities() throws Exception { - List entities = Arrays.asList(DetectEntities.DOB, DetectEntities.DATE); - DateTransformation dateTransformation = new DateTransformation(20, 5, entities); - Transformations transformations = new Transformations(dateTransformation); - java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); - method.setAccessible(true); - Object result = method.invoke(vaultClient, transformations); - Assert.assertNotNull(result); - com.skyflow.generated.rest.types.Transformations restTransform = (com.skyflow.generated.rest.types.Transformations) result; - Assert.assertEquals(2, restTransform.getShiftDates().get().getEntityTypes().get().size()); - } - - @Test - public void testGetDeidentifyGenericFileRequest_AllFields() throws SkyflowException { - File file = new File("test.custom"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .allowRegexList(Arrays.asList("a.*")) - .restrictRegexList(Arrays.asList("b.*")) - .build(); - - String vaultId = "vault123"; - String base64Content = "base64string"; - String fileExtension = "txt"; - - com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest genericRequest = - vaultClient.getDeidentifyGenericFileRequest(request, vaultId, base64Content, fileExtension); - - Assert.assertEquals(vaultId, genericRequest.getVaultId()); - Assert.assertEquals(base64Content, genericRequest.getFile().getBase64()); - Assert.assertNotNull(genericRequest.getEntityTypes()); - Assert.assertNotNull(genericRequest.getTokenType()); - Assert.assertTrue(genericRequest.getAllowRegex().isPresent()); - Assert.assertTrue(genericRequest.getRestrictRegex().isPresent()); - } - // --- unsupported file extension must throw SkyflowException, not raw IllegalArgumentException --- - @Test - public void testGetDeidentifyGenericFileRequest_UnsupportedExtensionThrowsSkyflowException() { - File file = new File("test.xyz"); - FileInput fileInput = FileInput.builder().file(file).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); - - try { - vaultClient.getDeidentifyGenericFileRequest(request, "vault123", "base64string", "xyz"); - Assert.fail("Should have thrown an exception"); - } catch (SkyflowException e) { - Assert.assertNotNull(e.getMessage()); - } catch (IllegalArgumentException e) { - Assert.fail("should throw SkyflowException, not raw IllegalArgumentException: " + e); - } - } - - @Test - public void testMapAudioDataFormat_mp3() throws Exception { - java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); - method.setAccessible(true); - Object result = method.invoke(vaultClient, "mp3"); - Assert.assertEquals(FileDataDeidentifyAudioDataFormat.MP_3, result); - } - - @Test - public void testMapAudioDataFormat_wav() throws Exception { - java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); - method.setAccessible(true); - Object result = method.invoke(vaultClient, "wav"); - Assert.assertEquals(FileDataDeidentifyAudioDataFormat.WAV, result); - } - - @Test - public void testMapAudioDataFormat_invalid() throws Exception { - java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); - method.setAccessible(true); - try { - method.invoke(vaultClient, "ogg"); - Assert.fail("Should throw SkyflowException for invalid audio type"); - } catch (Exception e) { - Throwable cause = e.getCause(); - Assert.assertTrue(cause instanceof SkyflowException); - } - } - // Fields moved to base classes (e.g. common.BaseVaultClient) aren't found by // getDeclaredField on the subclass, so walk up the hierarchy. private java.lang.reflect.Field findDeclaredField(Class clazz, String fieldName) throws NoSuchFieldException { @@ -958,67 +370,6 @@ public void testGetFileForFileUpload_withFileObject() { } } - @Test - public void testGetDeidentifyImageRequest_withMaskingMethod() { - try { - java.io.File file = new java.io.File("test.jpg"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .maskingMethod(MaskingMethod.BLACKBOX) - .outputProcessedImage(true) - .build(); - - DeidentifyFileImageRequestDeidentifyImage imageRequest = - vaultClient.getDeidentifyImageRequest(request, vaultID, "base64content", "jpg"); - - Assert.assertNotNull(imageRequest); - Assert.assertTrue(imageRequest.getMaskingMethod().isPresent()); - } catch (Exception e) { - Assert.fail("Should not have thrown: " + e.getMessage()); - } - } - - @Test - public void testGetDeIdentifyTextResponse_withEntityScores() { - Locations location = Locations.builder() - .startIndex(0) - .endIndex(5) - .startIndexProcessed(0) - .endIndexProcessed(5) - .build(); - - Map scores = new HashMap<>(); - scores.put("EMAIL_ADDRESS", 0.95); - - StringResponseEntities entity = StringResponseEntities.builder() - .location(location) - .token("tok") - .value("val") - .entityType("EMAIL_ADDRESS") - .entityScores(scores) - .build(); - - DeidentifyStringResponse deidentifyResponse = DeidentifyStringResponse.builder() - .entities(Collections.singletonList(entity)) - .processedText("processed text") - .wordCount(2) - .characterCount(13) - .build(); - - DeidentifyTextResponse result = vaultClient.getDeIdentifyTextResponse(deidentifyResponse); - - Assert.assertNotNull(result); - Assert.assertEquals(1, result.getEntities().size()); - // Entity scores map lambda was invoked → getScores() should have the score - Assert.assertEquals(0.95, result.getEntities().get(0).getScores().get("EMAIL_ADDRESS"), 0.001); - } - @Test public void testUpdateExecutorInHTTP_interceptorAddsAuthorizationHeader() { try { @@ -1085,101 +436,4 @@ public void testGetFileForFileUpload_withNoFileInput_returnsNull() { } } - @Test - public void testGetDeidentifyImageRequest_withEntityOnlyNull_andEntityUniqueCounterNonEmpty() { - try { - java.io.File file = new java.io.File("test.jpg"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder() - .entityUniqueCounter(entities) - .build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .build(); - - DeidentifyFileImageRequestDeidentifyImage imageRequest = - vaultClient.getDeidentifyImageRequest(request, vaultID, "base64content", "jpg"); - - Assert.assertNotNull(imageRequest); - } catch (Exception e) { - Assert.fail("Should not have thrown: " + e.getMessage()); - } - } - - @Test - public void testGetDeidentifyImageRequest_withEmptyEntityOnlyList() { - try { - java.io.File file = new java.io.File("test.jpg"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder() - .entityOnly(Collections.emptyList()) - .entityUniqueCounter(Collections.emptyList()) - .build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .build(); - - DeidentifyFileImageRequestDeidentifyImage imageRequest = - vaultClient.getDeidentifyImageRequest(request, vaultID, "base64content", "jpg"); - Assert.assertNotNull(imageRequest); - } catch (Exception e) { - Assert.fail("Should not have thrown: " + e.getMessage()); - } - } - - @Test - public void testGetDeidentifyGenericFileRequest_withEmptyEntityLists() { - try { - java.io.File file = new java.io.File("test.pdf"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - TokenFormat tokenFormat = TokenFormat.builder() - .entityOnly(Collections.emptyList()) - .entityUniqueCounter(Collections.emptyList()) - .build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .tokenFormat(tokenFormat) - .build(); - - com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest result = - vaultClient.getDeidentifyGenericFileRequest(request, vaultID, "base64content", "pdf"); - Assert.assertNotNull(result); - } catch (Exception e) { - Assert.fail("Should not have thrown: " + e.getMessage()); - } - } - - @Test - public void testGetDeidentifyGenericFileRequest_withNullFileExtension() { - // Covers the `fileExtension != null ? ... : null` false branch at line 779. - // The ternary evaluates null, which is then passed to FileData.builder().dataFormat(null) - // which throws — confirming the null branch of the ternary was exercised. - java.io.File file = new java.io.File("test.pdf"); - FileInput fileInput = FileInput.builder().file(file).build(); - List entities = Arrays.asList(DetectEntities.NAME); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(entities) - .build(); - - try { - vaultClient.getDeidentifyGenericFileRequest(request, vaultID, "base64content", null); - Assert.fail("Expected exception from null dataFormat"); - } catch (Exception e) { - // null fileExtension → ternary false branch → null passed to dataFormat() → throws - Assert.assertNotNull(e.getMessage()); - } - } } diff --git a/skyvault/src/test/java/com/skyflow/enums/DeidentifyFileStatusTest.java b/skyvault/src/test/java/com/skyflow/enums/DeidentifyFileStatusTest.java deleted file mode 100644 index 6d70a17c..00000000 --- a/skyvault/src/test/java/com/skyflow/enums/DeidentifyFileStatusTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.skyflow.enums; - -import org.junit.Assert; -import org.junit.Test; - -public class DeidentifyFileStatusTest { - - @Test - public void testInProgress() { - Assert.assertEquals("IN_PROGRESS", DeidentifyFileStatus.IN_PROGRESS.value()); - } - - @Test - public void testFailed() { - Assert.assertEquals("FAILED", DeidentifyFileStatus.FAILED.value()); - } - - @Test - public void testSuccess() { - Assert.assertEquals("SUCCESS", DeidentifyFileStatus.SUCCESS.value()); - } - - @Test - public void testUnknown() { - Assert.assertEquals("UNKNOWN", DeidentifyFileStatus.UNKNOWN.value()); - } -} diff --git a/skyvault/src/test/java/com/skyflow/enums/DetectEntitiesTest.java b/skyvault/src/test/java/com/skyflow/enums/DetectEntitiesTest.java deleted file mode 100644 index 2bb29f0c..00000000 --- a/skyvault/src/test/java/com/skyflow/enums/DetectEntitiesTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.skyflow.enums; - -import org.junit.Assert; -import org.junit.Test; - -public class DetectEntitiesTest { - - @Test - public void testGetDetectEntities() { - Assert.assertEquals("account_number", DetectEntities.ACCOUNT_NUMBER.getDetectEntities()); - Assert.assertEquals("account_number", DetectEntities.ACCOUNT_NUMBER.toString()); - } - - @Test - public void testAll() { - Assert.assertEquals("all", DetectEntities.ALL.getDetectEntities()); - } - - @Test - public void testName() { - Assert.assertEquals("name", DetectEntities.NAME.getDetectEntities()); - Assert.assertEquals("name", DetectEntities.NAME.toString()); - } -} diff --git a/skyvault/src/test/java/com/skyflow/enums/DetectOutputTranscriptionsTest.java b/skyvault/src/test/java/com/skyflow/enums/DetectOutputTranscriptionsTest.java deleted file mode 100644 index 6df404ed..00000000 --- a/skyvault/src/test/java/com/skyflow/enums/DetectOutputTranscriptionsTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.skyflow.enums; - -import org.junit.Assert; -import org.junit.Test; - -public class DetectOutputTranscriptionsTest { - - @Test - public void testDiarizedTranscription() { - Assert.assertEquals("diarized_transcription", DetectOutputTranscriptions.DIARIZED_TRANSCRIPTION.getDetectOutputTranscriptions()); - Assert.assertEquals("diarized_transcription", DetectOutputTranscriptions.DIARIZED_TRANSCRIPTION.toString()); - } - - @Test - public void testMedicalDiarizedTranscription() { - Assert.assertEquals("medical_diarized_transcription", DetectOutputTranscriptions.MEDICAL_DIARIZED_TRANSCRIPTION.getDetectOutputTranscriptions()); - Assert.assertEquals("medical_diarized_transcription", DetectOutputTranscriptions.MEDICAL_DIARIZED_TRANSCRIPTION.toString()); - } - - @Test - public void testMedicalTranscription() { - Assert.assertEquals("medical_transcription", DetectOutputTranscriptions.MEDICAL_TRANSCRIPTION.getDetectOutputTranscriptions()); - Assert.assertEquals("medical_transcription", DetectOutputTranscriptions.MEDICAL_TRANSCRIPTION.toString()); - } - - @Test - public void testTranscription() { - Assert.assertEquals("transcription", DetectOutputTranscriptions.TRANSCRIPTION.getDetectOutputTranscriptions()); - Assert.assertEquals("transcription", DetectOutputTranscriptions.TRANSCRIPTION.toString()); - } -} diff --git a/skyvault/src/test/java/com/skyflow/enums/MaskingMethodTest.java b/skyvault/src/test/java/com/skyflow/enums/MaskingMethodTest.java deleted file mode 100644 index f675189e..00000000 --- a/skyvault/src/test/java/com/skyflow/enums/MaskingMethodTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.skyflow.enums; - -import org.junit.Assert; -import org.junit.Test; - -public class MaskingMethodTest { - - @Test - public void testBlackbox() { - Assert.assertEquals("blackbox", MaskingMethod.BLACKBOX.getMaskingMethod()); - Assert.assertEquals("blackbox", MaskingMethod.BLACKBOX.toString()); - } - - @Test - public void testBlur() { - Assert.assertEquals("blur", MaskingMethod.BLUR.getMaskingMethod()); - Assert.assertEquals("blur", MaskingMethod.BLUR.toString()); - } -} diff --git a/skyvault/src/test/java/com/skyflow/enums/TokenTypeTest.java b/skyvault/src/test/java/com/skyflow/enums/TokenTypeTest.java deleted file mode 100644 index 4f5c0901..00000000 --- a/skyvault/src/test/java/com/skyflow/enums/TokenTypeTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.skyflow.enums; - -import org.junit.Assert; -import org.junit.Test; - -public class TokenTypeTest { - - @Test - public void testVaultToken() { - Assert.assertEquals("vault_token", TokenType.VAULT_TOKEN.getTokenType()); - Assert.assertEquals("vault_token", TokenType.VAULT_TOKEN.toString()); - } - - @Test - public void testEntityUniqueCounter() { - Assert.assertEquals("entity_unq_counter", TokenType.ENTITY_UNIQUE_COUNTER.getTokenType()); - Assert.assertEquals("entity_unq_counter", TokenType.ENTITY_UNIQUE_COUNTER.toString()); - } - - @Test - public void testEntityOnly() { - Assert.assertEquals("entity_only", TokenType.ENTITY_ONLY.getTokenType()); - Assert.assertEquals("entity_only", TokenType.ENTITY_ONLY.toString()); - } - - @Test - public void testGetDefault() { - Assert.assertEquals(TokenType.ENTITY_UNIQUE_COUNTER.getTokenType(), TokenType.VAULT_TOKEN.getDefault()); - } -} diff --git a/skyvault/src/test/java/com/skyflow/utils/UtilsTests.java b/skyvault/src/test/java/com/skyflow/utils/UtilsTests.java index d1e1c725..7ac13ec7 100644 --- a/skyvault/src/test/java/com/skyflow/utils/UtilsTests.java +++ b/skyvault/src/test/java/com/skyflow/utils/UtilsTests.java @@ -76,8 +76,12 @@ public void testGetMetrics() { @Test public void testGetMetricsWithException() { + // Clearing System Properties explicitly to throw exception. They are restored afterwards: the JDK's + // socket layer reads os.name on first use, and a null value breaks every later test that opens a socket. + String osName = System.getProperty("os.name"); + String osVersion = System.getProperty("os.version"); + String javaVersion = System.getProperty("java.version"); try { - // Clearing System Properties explicitly to throw exception System.clearProperty("os.name"); System.clearProperty("os.version"); System.clearProperty("java.version"); @@ -89,6 +93,18 @@ public void testGetMetricsWithException() { Assert.assertTrue(metrics.get(Constants.SDK_METRIC_CLIENT_OS_DETAILS).getAsString().isEmpty()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); + } finally { + restoreProperty("os.name", osName); + restoreProperty("os.version", osVersion); + restoreProperty("java.version", javaVersion); + } + } + + private static void restoreProperty(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); } } } diff --git a/skyvault/src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java b/skyvault/src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java deleted file mode 100644 index f0347eeb..00000000 --- a/skyvault/src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java +++ /dev/null @@ -1,466 +0,0 @@ -package com.skyflow.vault.controller; - -import com.skyflow.config.BaseVaultConfig; -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; -import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.types.DeidentifiedFileOutput; -import com.skyflow.generated.rest.types.DetectRunsResponse; -import com.skyflow.generated.rest.types.DetectRunsResponseStatus; -import com.skyflow.vault.detect.AudioBleep; -import com.skyflow.vault.detect.DeidentifyFileRequest; -import com.skyflow.vault.detect.DeidentifyFileResponse; -import com.skyflow.vault.detect.FileInput; -import com.skyflow.vault.detect.GetDetectRunRequest; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.lang.reflect.Method; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Collections; - -public class DetectControllerFileTests { - private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; - private static String vaultID = null; - private static String clusterID = null; - private static VaultConfig vaultConfig = null; - private static DetectController detectController = null; - - @BeforeClass - public static void setup() { - vaultID = "vault123"; - clusterID = "cluster123"; - - Credentials credentials = new Credentials(); - credentials.setToken("valid-token"); - - vaultConfig = new VaultConfig(); - vaultConfig.setVaultId(vaultID); - vaultConfig.setClusterId(clusterID); - vaultConfig.setEnv(com.skyflow.enums.Env.DEV); - vaultConfig.setCredentials(credentials); - - detectController = new DetectController(vaultConfig, credentials); - } - - @Test - public void testUnreadableFileInDeidentifyFileRequest() { - try { - File file = new File("unreadable.txt") { - @Override - public boolean exists() { return true; } - @Override - public boolean isFile() { return true; } - @Override - public boolean canRead() { return false; } - }; - FileInput fileInput = FileInput.builder().file(file).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException | RuntimeException e) { - // Depending on implementation, could be SkyflowException or RuntimeException - Assert.assertTrue(e.getMessage().contains("not readable") || e.getMessage().contains("unreadable.txt")); - } - } - - @Test - public void testNullEntitiesInDeidentifyFileRequest() { - try { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(new ArrayList<>()) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testNullRequest() { - try { - detectController.deidentifyFile(null); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testFileInputBothFileAndFilePathNull() { - try { - FileInput fileInput = FileInput.builder().build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); - detectController.deidentifyFile(request); - Assert.fail("Should have thrown an exception for both file and filePath being null"); - } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains(ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage())); - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testFileInputBothFileAndFilePathProvided() { - try { - java.io.File file = java.io.File.createTempFile("test", ".txt"); - String filePath = file.getAbsolutePath(); - FileInput fileInput = FileInput.builder().file(file).filePath(filePath).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); - detectController.deidentifyFile(request); - Assert.fail("Should have thrown an exception for both file and filePath being provided"); - } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains(ErrorMessage.BothFileAndFilePathProvided.getMessage())); - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testFileInputEmptyFilePath() { - try { - FileInput fileInput = FileInput.builder().filePath("").build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); - detectController.deidentifyFile(request); - Assert.fail("Should have thrown an exception for empty filePath"); - } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains(ErrorMessage.InvalidFilePath.getMessage())); - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testFileInputNonExistentFile() { - try { - java.io.File file = new java.io.File("nonexistent.txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); - detectController.deidentifyFile(request); - Assert.fail("Should have thrown an exception for non-existent file"); - } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains(ErrorMessage.FileNotFoundToDeidentify.getMessage())); - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testFileInputUnreadableFile() { - try { - java.io.File file = new java.io.File("unreadable.txt") { - @Override - public boolean exists() { return true; } - @Override - public boolean isFile() { return true; } - @Override - public boolean canRead() { return false; } - }; - FileInput fileInput = FileInput.builder().file(file).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); - detectController.deidentifyFile(request); - Assert.fail("Should have thrown an exception for unreadable file"); - } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains(ErrorMessage.FileNotReadableToDeidentify.getMessage())); - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testNonExistentFileInDeidentifyFileRequest() { - try { - File file = new File("nonexistent.txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testInvalidPixelDensity() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .pixelDensity(-1) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testInvalidMaxResolution() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .maxResolution(-1) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testInvalidBleepFrequency() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - AudioBleep bleep = AudioBleep.builder().build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .bleep(bleep) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testInvalidOutputDirectory() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .outputDirectory("not/a/real/dir") - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testInvalidWaitTime() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .waitTime(-1) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testWaitTimeExceedsLimit() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .waitTime(100) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testNullGetDetectRunRequest() { - try { - detectController.getDetectRun(null); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testEmptyRunIdInGetDetectRunRequest() { - try { - GetDetectRunRequest request = GetDetectRunRequest.builder().build(); - detectController.getDetectRun(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testNullRunIdInGetDetectRunRequest() { - try { - GetDetectRunRequest request = GetDetectRunRequest.builder().runId(null).build(); - detectController.getDetectRun(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - } - - @Test - public void testInvalidBleepGain() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(-1.0).startPadding(0.1).stopPadding(0.1).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .bleep(bleep) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testInvalidBleepStartPadding() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(0.5).startPadding(-0.1).stopPadding(0.1).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .bleep(bleep) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testInvalidBleepStopPadding() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - try { - AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(0.5).startPadding(0.1).stopPadding(-0.1).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .bleep(bleep) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - } - - @Test - public void testOutputDirectoryNotDirectory() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - File notADir = File.createTempFile("notadir", ".txt"); - try { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .outputDirectory(notADir.getAbsolutePath()) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } - file.delete(); - notADir.delete(); - } - - @Test - public void testOutputDirectoryNotWritable() throws Exception { - File file = File.createTempFile("test", ".txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - File dir = Files.createTempDirectory("notwritabledir").toFile(); - dir.setWritable(false); - try { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .outputDirectory(dir.getAbsolutePath()) - .build(); - detectController.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); - } finally { - dir.setWritable(true); - file.delete(); - dir.delete(); - } - } - - // C1 regression: the dead statement response.getEntities().get(0) has been removed. - // The short-form constructor produces null entities; the guarded block at the call site - // handles that safely. - @Test - public void testDeidentifyFileResponseNullEntitiesDoesNotThrow() { - DeidentifyFileResponse response = new DeidentifyFileResponse("run-id", "IN_PROGRESS"); - Assert.assertNull("Entities must be null from short-form constructor", response.getEntities()); - } - - // C2: getFirstOutput must return null (not throw NoSuchElementException) when output is absent. - @Test - public void testGetFirstOutputReturnsNullWhenOutputAbsent() throws Exception { - DetectRunsResponse response = DetectRunsResponse.builder().build(); - Method method = DetectController.class.getDeclaredMethod("getFirstOutput", DetectRunsResponse.class); - method.setAccessible(true); - DeidentifiedFileOutput result = (DeidentifiedFileOutput) method.invoke(null, response); - Assert.assertNull("getFirstOutput must return null when output Optional is absent", result); - } - - // C2: getFirstOutput must return null when output list is present but empty. - @Test - public void testGetFirstOutputReturnsNullWhenOutputListEmpty() throws Exception { - DetectRunsResponse response = DetectRunsResponse.builder() - .output(Collections.emptyList()) - .build(); - Method method = DetectController.class.getDeclaredMethod("getFirstOutput", DetectRunsResponse.class); - method.setAccessible(true); - DeidentifiedFileOutput result = (DeidentifiedFileOutput) method.invoke(null, response); - Assert.assertNull("getFirstOutput must return null when output list is empty", result); - } - - // C3: parseDeidentifyFileResponse must not throw when processedFileExtension is absent; - // it should fall back to the UNKNOWN sentinel value. - @Test - public void testParseDeidentifyFileResponseFallsBackWhenExtensionAbsent() throws Exception { - DetectRunsResponse response = DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.SUCCESS) - .output(Collections.singletonList(DeidentifiedFileOutput.builder().build())) - .build(); - - Method method = DetectController.class.getDeclaredMethod( - "parseDeidentifyFileResponse", DetectRunsResponse.class, String.class, String.class); - method.setAccessible(true); - DeidentifyFileResponse result = (DeidentifyFileResponse) method.invoke(null, response, "run-id", "SUCCESS"); - - Assert.assertNotNull("Response must not be null", result); - Assert.assertEquals("Extension must fall back to UNKNOWN when absent", - DetectRunsResponseStatus.UNKNOWN.toString(), result.getExtension()); - } -} \ No newline at end of file diff --git a/skyvault/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java b/skyvault/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java index b6c504af..b31002ef 100644 --- a/skyvault/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java +++ b/skyvault/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java @@ -1,1138 +1,632 @@ package com.skyflow.vault.controller; import com.skyflow.Skyflow; -import com.skyflow.VaultClient; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.DetectEntities; +import com.skyflow.detect.CheckGuardrailsRequest; +import com.skyflow.detect.CheckGuardrailsResponse; +import com.skyflow.detect.DataSourceType; +import com.skyflow.detect.DeidentificationType; +import com.skyflow.detect.DeidentifyFileRequest; +import com.skyflow.detect.DeidentifyFileResponse; +import com.skyflow.detect.DeidentifyStringRequest; +import com.skyflow.detect.DeidentifyStringResponse; +import com.skyflow.detect.Detect; +import com.skyflow.detect.DetectConfiguration; +import com.skyflow.detect.DetectRunStatus; +import com.skyflow.detect.Entity; +import com.skyflow.detect.EntityType; +import com.skyflow.detect.FileDataFormat; +import com.skyflow.detect.GetRunRequest; +import com.skyflow.detect.GetRunResponse; +import com.skyflow.detect.GuardrailsValidation; +import com.skyflow.detect.PollOptions; +import com.skyflow.detect.RedactionLevel; +import com.skyflow.detect.ReidentifyFileRequest; +import com.skyflow.detect.ReidentifyFileResponse; +import com.skyflow.detect.ReidentifyStringRequest; +import com.skyflow.detect.ReidentifyStringResponse; import com.skyflow.enums.Env; -import com.skyflow.enums.LogLevel; -import com.skyflow.errors.ErrorMessage; -import com.skyflow.errors.HttpStatus; +import com.skyflow.errors.BaseErrorMessage; +import com.skyflow.errors.ErrorCode; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.core.ApiClientApiException; -import com.skyflow.generated.rest.core.ApiClientException; -import com.skyflow.generated.rest.resources.files.FilesClient; -import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; -import com.skyflow.generated.rest.resources.strings.StringsClient; -import com.skyflow.generated.rest.types.DeidentifiedFileOutput; -import com.skyflow.generated.rest.types.DeidentifiedFileOutputProcessedFileExtension; -import com.skyflow.generated.rest.types.DeidentifyStringResponse; -import com.skyflow.generated.rest.types.DetectRunsResponse; -import com.skyflow.generated.rest.types.DetectRunsResponseOutputType; -import com.skyflow.generated.rest.types.DetectRunsResponseStatus; -import com.skyflow.generated.rest.types.IdentifyResponse; -import com.skyflow.generated.rest.types.WordCharacterCount; -import com.skyflow.utils.Constants; -import com.skyflow.utils.Utils; -import com.skyflow.vault.detect.DeidentifyTextRequest; -import com.skyflow.vault.detect.DeidentifyTextResponse; -import com.skyflow.vault.detect.DeidentifyFileResponse; -import com.skyflow.vault.detect.GetDetectRunRequest; -import com.skyflow.vault.detect.ReidentifyTextRequest; -import com.skyflow.vault.detect.ReidentifyTextResponse; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Rule; import org.junit.Test; -import org.mockito.Mockito; +import org.junit.rules.TemporaryFolder; import java.io.File; -import java.lang.reflect.Field; import java.nio.file.Files; import java.util.Base64; -import java.util.Collections; - -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.vault.detect.DeidentifyFileRequest; -import com.skyflow.vault.detect.FileInput; -import com.skyflow.vault.detect.TokenFormat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; +import java.util.Arrays; +import java.util.Collections; public class DetectControllerTests { - private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; - private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - private static String vaultID = null; - private static String clusterID = null; - private static VaultConfig vaultConfig = null; - private static Skyflow skyflowClient = null; - - @BeforeClass - public static void setup() throws SkyflowException { - vaultID = "vault123"; - clusterID = "cluster123"; - - Credentials credentials = new Credentials(); - credentials.setToken("valid-token"); - - vaultConfig = new VaultConfig(); - vaultConfig.setVaultId(vaultID); - vaultConfig.setClusterId(clusterID); - vaultConfig.setEnv(Env.DEV); - vaultConfig.setCredentials(credentials); - - skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addVaultConfig(vaultConfig) - .build(); - } - - // ─── helper: build a DetectController with a mocked ApiClient ───────────── - private static DetectController createDetectControllerWithMock(ApiClient mockApiClient) throws Exception { - Credentials creds = new Credentials(); - creds.setApiKey("sky-ab123-abcd1234cdef1234abcd4321cdef4321"); + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + private static VaultConfig vaultConfig(String vaultId) { VaultConfig config = new VaultConfig(); - config.setVaultId(vaultID); - config.setClusterId(clusterID); - config.setEnv(Env.DEV); - - DetectController controller = new DetectController(config, creds); - Field f = VaultClient.class.getDeclaredField("apiClient"); - f.setAccessible(true); - f.set(controller, mockApiClient); - return controller; + config.setVaultId(vaultId); + config.setClusterId("cluster123"); + config.setEnv(Env.PROD); + return config; } - // ─── deidentifyText — validation ────────────────────────────────────────── - @Test - public void testNullTextInRequestInDeidentifyStringMethod() { + public void detectAccessorResolvesConfiguredVaults() throws SkyflowException { + Skyflow client = Skyflow.builder() + .addVaultConfig(vaultConfig("vault-a")) + .addVaultConfig(vaultConfig("vault-b")) + .build(); + Assert.assertNotNull(client.detect()); + Assert.assertSame(client.detect(), client.detect("vault-a")); + Assert.assertNotSame(client.detect("vault-a"), client.detect("vault-b")); try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text(null).build(); - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.detect(vaultID).deidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); + client.detect("vault-c"); + Assert.fail("expected SkyflowException"); } catch (SkyflowException e) { - Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.InvalidTextInDeIdentify.getMessage(), Constants.SDK_PREFIX), - e.getMessage() - ); - Assert.assertNull(e.getRequestId()); - Assert.assertNull(e.getGrpcCode()); - Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @Test - public void testEmptyTextInRequestInDeidentifyStringMethod() { + public void detectAccessorFollowsVaultConfigRemoval() throws SkyflowException { + Skyflow client = Skyflow.builder().addVaultConfig(vaultConfig("vault-a")).build(); + client.removeVaultConfig("vault-a"); try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.detect(vaultID).deidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); + client.detect(); + Assert.fail("expected SkyflowException"); } catch (SkyflowException e) { - Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.InvalidTextInDeIdentify.getMessage(), Constants.SDK_PREFIX), - e.getMessage() - ); - Assert.assertNull(e.getRequestId()); - Assert.assertNull(e.getGrpcCode()); - Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + Assert.assertEquals(BaseErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } - // ─── deidentifyText — happy path ────────────────────────────────────────── - @Test - public void testDeidentifyTextHappyPath() throws Exception { - StringsClient mockStringsClient = Mockito.mock(StringsClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.strings()).thenReturn(mockStringsClient); - - DeidentifyStringResponse fakeResponse = DeidentifyStringResponse.builder() - .processedText("hello [REDACTED]") - .wordCount(2) - .characterCount(16) - .build(); - - when(mockStringsClient.deidentifyString(any(), any())).thenReturn(fakeResponse); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("hello world").build(); - + public void deidentifyStringValidatesBeforeResolvingCredentials() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), (Credentials) null); try { - DeidentifyTextResponse response = controller.deidentifyText(request); - Assert.assertNotNull(response); - Assert.assertEquals("hello [REDACTED]", response.getProcessedText()); - Assert.assertEquals(2, response.getWordCount()); - Assert.assertEquals(16, response.getCharCount()); + controller.deidentifyString(DeidentifyStringRequest.builder().text(" ").configurationId("cfg").build()); + Assert.fail("expected SkyflowException"); } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.InvalidTextInDeidentifyString.getMessage(), e.getMessage()); } } - // ─── deidentifyText — API error path ────────────────────────────────────── - @Test - public void testDeidentifyTextApiError() throws Exception { - StringsClient mockStringsClient = Mockito.mock(StringsClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.strings()).thenReturn(mockStringsClient); - - int expectedStatusCode = 403; - when(mockStringsClient.deidentifyString(any(), any())) - .thenThrow(new ApiClientApiException("Forbidden", expectedStatusCode, "access denied")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("hello world").build(); - + public void reidentifyStringValidatesBeforeResolvingCredentials() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), (Credentials) null); try { - controller.deidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); + controller.reidentifyString(ReidentifyStringRequest.builder().text(" ").build()); + Assert.fail("expected SkyflowException"); } catch (SkyflowException e) { - Assert.assertEquals(expectedStatusCode, e.getHttpCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.InvalidTextInReidentifyString.getMessage(), e.getMessage()); } } + /** + * Null credentials would make the SDK fall back to SKYFLOW_CREDENTIALS from the environment or a + * .env file, which CI provides, so the outcome would depend on the machine. An explicitly empty + * {@link Credentials} is rejected by validation the same way everywhere, before any network call. + */ @Test - public void testDeidentifyTextApiError500() throws Exception { - StringsClient mockStringsClient = Mockito.mock(StringsClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.strings()).thenReturn(mockStringsClient); - - int expectedStatusCode = 500; - when(mockStringsClient.deidentifyString(any(), any())) - .thenThrow(new ApiClientApiException("Internal Server Error", expectedStatusCode, "server error body")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("some text").build(); - + public void missingCredentialsSurfaceAsSkyflowExceptionWithoutNetworkCall() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), emptyCredentials()); try { - controller.deidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); + controller.reidentifyString(ReidentifyStringRequest.builder().text("[NAME_1]").build()); + Assert.fail("expected SkyflowException"); } catch (SkyflowException e) { - Assert.assertEquals(expectedStatusCode, e.getHttpCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); } } - @Test - public void testDeidentifyTextApiClientException() throws Exception { - // Network-level failure (no HTTP response), as opposed to ApiClientApiException's - // rejected-with-a-status-code failure above. - StringsClient mockStringsClient = Mockito.mock(StringsClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.strings()).thenReturn(mockStringsClient); - - when(mockStringsClient.deidentifyString(any(), any())) - .thenThrow(new ApiClientException("Network error executing HTTP request")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("hello world").build(); - - try { - controller.deidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertTrue(e.getCause() instanceof ApiClientException); - } + /** Credentials with no path, string, token or API key set. */ + private static Credentials emptyCredentials() { + return new Credentials(); } - // ─── reidentifyText — validation ────────────────────────────────────────── - - @Test - public void testNullTextInRequestInReidentifyStringMethod() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder().text(null).build(); - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.detect(vaultID).reidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.InvalidTextInReIdentify.getMessage(), Constants.SDK_PREFIX), - e.getMessage() - ); - Assert.assertNull(e.getRequestId()); - Assert.assertNull(e.getGrpcCode()); - Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); - } + /** API-key credentials resolve without a token exchange, so the only network call is the Detect request. */ + private static Credentials apiKeyCredentials() { + Credentials credentials = new Credentials(); + credentials.setApiKey("sky-abcde-0123456789abcdef0123456789abcdef"); + return credentials; } - @Test - public void testEmptyTextInRequestInReidentifyStringMethod() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder().text("").build(); - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.detect(vaultID).reidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.InvalidTextInReIdentify.getMessage(), Constants.SDK_PREFIX), - e.getMessage() - ); - Assert.assertNull(e.getRequestId()); - Assert.assertNull(e.getGrpcCode()); - Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); - } + private static DetectController controllerFor(MockWebServer server) { + VaultConfig config = vaultConfig("vault-1"); + DetectController controller = new DetectController(config, apiKeyCredentials(), server.url("").toString()); + controller.setCommonHttpConfig(null, 0, null, null); + return controller; } - // ─── reidentifyText — happy path ────────────────────────────────────────── - - @Test - public void testReidentifyTextHappyPath() throws Exception { - StringsClient mockStringsClient = Mockito.mock(StringsClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.strings()).thenReturn(mockStringsClient); - - IdentifyResponse fakeResponse = IdentifyResponse.builder().text("original text").build(); - when(mockStringsClient.reidentifyString(any(), any())).thenReturn(fakeResponse); + // ─── Detect V2 methods, exercised through the skyvault controller ────────── + // These prove the skyvault wiring (cluster-derived vault URL, API-key credentials, + // skyvault SDK metrics header) end to end, not just the shared base logic. - DetectController controller = createDetectControllerWithMock(mockApiClient); - ReidentifyTextRequest request = ReidentifyTextRequest.builder().text("tokenized text").build(); + private static final String API_KEY = "sky-abcde-0123456789abcdef0123456789abcdef"; - try { - ReidentifyTextResponse response = controller.reidentifyText(request); - Assert.assertNotNull(response); - Assert.assertEquals("original text", response.getProcessedText()); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); - } + private static void assertCommonHeaders(RecordedRequest recorded, String method, String path) { + Assert.assertEquals(method, recorded.getMethod()); + Assert.assertEquals(path, recorded.getPath()); + Assert.assertEquals("Bearer " + API_KEY, recorded.getHeader("Authorization")); + String metrics = recorded.getHeader("sky-metadata"); + Assert.assertNotNull(metrics); + Assert.assertTrue(metrics, metrics.contains("skyflow-java@")); } - // ─── reidentifyText — API error path ────────────────────────────────────── - @Test - public void testReidentifyTextApiError() throws Exception { - StringsClient mockStringsClient = Mockito.mock(StringsClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.strings()).thenReturn(mockStringsClient); - - int expectedStatusCode = 401; - when(mockStringsClient.reidentifyString(any(), any())) - .thenThrow(new ApiClientApiException("Unauthorized", expectedStatusCode, "unauthorized body")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - ReidentifyTextRequest request = ReidentifyTextRequest.builder().text("some text").build(); - + public void deidentifyStringRoundTripWithStoredConfiguration() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - controller.reidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(expectedStatusCode, e.getHttpCode()); + server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") + .setBody("{\"processedText\":\"My name is [NAME_1].\"," + + "\"entities\":[{\"token\":\"NAME_1\",\"value\":\"John Doe\",\"entityType\":\"NAME\"," + + "\"location\":{\"startIndex\":11,\"endIndex\":19,\"startIndexProcessed\":11,\"endIndexProcessed\":19}," + + "\"entityScores\":{\"NAME\":0.98}}]," + + "\"metrics\":{\"wordCount\":4,\"characterCount\":20}}")); + + DeidentifyStringResponse response = controllerFor(server).deidentifyString(DeidentifyStringRequest.builder() + .text("My name is John Doe.").configurationId("cfg-123").build()); + + Assert.assertEquals("My name is [NAME_1].", response.getProcessedText()); + Assert.assertEquals(1, response.getEntities().size()); + Assert.assertEquals("NAME_1", response.getEntities().get(0).getToken()); + Assert.assertEquals("John Doe", response.getEntities().get(0).getValue()); + Assert.assertEquals("NAME", response.getEntities().get(0).getEntityType()); + Assert.assertEquals(Integer.valueOf(11), response.getEntities().get(0).getLocation().getStartIndex()); + Assert.assertEquals(Integer.valueOf(19), response.getEntities().get(0).getLocation().getEndIndexProcessed()); + Assert.assertEquals(0.98, response.getEntities().get(0).getEntityScores().get("NAME"), 1e-9); + Assert.assertEquals(Integer.valueOf(4), response.getMetrics().getWordCount()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "POST", "/v2/detect/deidentify/string"); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"text\":\"My name is John Doe.\"")); + Assert.assertTrue(body, body.contains("\"configurationId\":\"cfg-123\"")); + Assert.assertFalse(body, body.contains("\"configuration\":")); + } finally { + server.shutdown(); } } @Test - public void testReidentifyTextApiError500() throws Exception { - StringsClient mockStringsClient = Mockito.mock(StringsClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.strings()).thenReturn(mockStringsClient); - - int expectedStatusCode = 500; - when(mockStringsClient.reidentifyString(any(), any())) - .thenThrow(new ApiClientApiException("Internal Server Error", expectedStatusCode, "server error body")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - ReidentifyTextRequest request = ReidentifyTextRequest.builder().text("some text").build(); - + public void deidentifyStringRoundTripWithInlineConfigurationScopedToVault() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - controller.reidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(expectedStatusCode, e.getHttpCode()); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"processedText\":\"[NAME_1]\"}")); + + DeidentifyStringResponse response = controllerFor(server).deidentifyString(DeidentifyStringRequest.builder() + .text("John") + .configuration(DetectConfiguration.builder() + .detect(Detect.builder().entities(Collections.singletonList( + Entity.builder().entityType(EntityType.NAME) + .deidentificationType(DeidentificationType.VAULT_TOKEN) + .destination("names").build())).build()) + .build()) + .build()); + + Assert.assertEquals("[NAME_1]", response.getProcessedText()); + Assert.assertTrue(response.getEntities().isEmpty()); + Assert.assertNull(response.getMetrics()); + + String body = server.takeRequest().getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"configuration\":{")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); // injected by the controller + Assert.assertTrue(body, body.contains("\"entityType\":\"NAME\"")); + Assert.assertTrue(body, body.contains("\"deidentificationType\":\"VAULT_TOKEN\"")); + Assert.assertTrue(body, body.contains("\"destination\":\"names\"")); + Assert.assertFalse(body, body.contains("configurationId")); + } finally { + server.shutdown(); } } @Test - public void testReidentifyTextApiClientException() throws Exception { - StringsClient mockStringsClient = Mockito.mock(StringsClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.strings()).thenReturn(mockStringsClient); - - when(mockStringsClient.reidentifyString(any(), any())) - .thenThrow(new ApiClientException("Network error executing HTTP request")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - ReidentifyTextRequest request = ReidentifyTextRequest.builder().text("some text").build(); - + public void reidentifyStringRoundTrip() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - controller.reidentifyText(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertTrue(e.getCause() instanceof ApiClientException); + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"processedText\":\"My name is J**n D*e.\",\"metrics\":{\"wordCount\":5}}")); + + ReidentifyStringResponse response = controllerFor(server).reidentifyString(ReidentifyStringRequest.builder() + .text("My name is [NAME_1].") + .redactionLevel(Collections.singletonList( + RedactionLevel.builder().tokenGroupName("names").redactionPattern("mask").build())) + .build()); + + Assert.assertEquals("My name is J**n D*e.", response.getProcessedText()); + Assert.assertEquals(Integer.valueOf(5), response.getMetrics().getWordCount()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "POST", "/v2/detect/reidentify/string"); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"text\":\"My name is [NAME_1].\"")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(body, body.contains("\"tokenGroupName\":\"names\"")); + Assert.assertTrue(body, body.contains("\"redactionPattern\":\"mask\"")); + } finally { + server.shutdown(); } } - // ─── getDetectRun — validation ──────────────────────────────────────────── - @Test - public void testNullRunIdInGetDetectRunRequest() { + public void getRunRoundTripQueriesByIdScopedToVault() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - GetDetectRunRequest request = GetDetectRunRequest.builder().runId(null).build(); - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.detect(vaultID).getDetectRun(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"status\":\"SUCCESS\",\"outputType\":\"BASE64\"," + + "\"output\":[{\"processedFile\":\"UERG\",\"processedFileType\":\"REDACTED_FILE\",\"processedFileExtension\":\"pdf\"}]," + + "\"metrics\":{\"pages\":3}}")); + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"status\":\"FAILED\",\"message\":\"unsupported file\"}")); + + DetectController controller = controllerFor(server); + GetRunResponse done = controller.getRun(GetRunRequest.builder().runId(" run-42 ").build()); + Assert.assertEquals("run-42", done.getRunId()); + Assert.assertEquals(DetectRunStatus.SUCCESS, done.getStatus()); + Assert.assertEquals(DataSourceType.BASE64, done.getOutputType()); + Assert.assertEquals("UERG", done.getOutput().get(0).getProcessedFile()); + Assert.assertEquals("REDACTED_FILE", done.getOutput().get(0).getProcessedFileType()); + Assert.assertEquals(FileDataFormat.PDF, done.getOutput().get(0).getProcessedFileExtension()); + Assert.assertEquals(Integer.valueOf(3), done.getMetrics().getPages()); + Assert.assertNull(done.getMessage()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "GET", "/v2/detect/runs/run-42?vaultId=vault-1"); + Assert.assertEquals(0L, recorded.getBodySize()); + + GetRunResponse failed = controller.getRun(GetRunRequest.builder().runId("run-43").build()); + Assert.assertEquals(DetectRunStatus.FAILED, failed.getStatus()); + Assert.assertEquals("unsupported file", failed.getMessage()); + Assert.assertTrue(failed.getOutput().isEmpty()); + Assert.assertNull(failed.getOutputType()); + Assert.assertEquals("/v2/detect/runs/run-43?vaultId=vault-1", server.takeRequest().getPath()); + } finally { + server.shutdown(); } } @Test - public void testEmptyRunIdInGetDetectRunRequest() { + public void checkGuardrailsRoundTrip() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - GetDetectRunRequest request = GetDetectRunRequest.builder().runId("").build(); - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.detect(vaultID).getDetectRun(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"text\":\"tell me about politics\",\"validation\":\"FAILED\",\"toxic\":false,\"deniedTopic\":true}")); + server.enqueue(new MockResponse().setResponseCode(200) + .setBody("{\"text\":\"hello\",\"validation\":\"PASSED\"}")); + + DetectController controller = controllerFor(server); + CheckGuardrailsResponse blocked = controller.checkGuardrails(CheckGuardrailsRequest.builder() + .text("tell me about politics").checkToxicity(true).denyTopics(Arrays.asList("politics", "religion")).build()); + Assert.assertEquals("tell me about politics", blocked.getText()); + Assert.assertEquals(GuardrailsValidation.FAILED, blocked.getValidation()); + Assert.assertEquals(Boolean.FALSE, blocked.getToxic()); + Assert.assertEquals(Boolean.TRUE, blocked.getDeniedTopic()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "POST", "/v2/detect/guardrails"); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"text\":\"tell me about politics\"")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(body, body.contains("\"checkToxicity\":true")); + Assert.assertTrue(body, body.contains("\"denyTopics\":[\"politics\",\"religion\"]")); + + CheckGuardrailsResponse passed = controller.checkGuardrails(CheckGuardrailsRequest.builder().text("hello").build()); + Assert.assertEquals(GuardrailsValidation.PASSED, passed.getValidation()); + Assert.assertNull(passed.getToxic()); + Assert.assertNull(passed.getDeniedTopic()); + String minimal = server.takeRequest().getBody().readUtf8(); + Assert.assertFalse(minimal, minimal.contains("checkToxicity")); + Assert.assertFalse(minimal, minimal.contains("denyTopics")); + } finally { + server.shutdown(); } } - // ─── getDetectRun — happy path (no output list) ─────────────────────────── - @Test - public void testGetDetectRunHappyPathNoOutput() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - - DetectRunsResponse fakeRunsResponse = DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.SUCCESS) - .outputType(DetectRunsResponseOutputType.BASE_64) - .size(10.5f) - .duration(1.2f) - .build(); - - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class))) - .thenReturn(fakeRunsResponse); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - GetDetectRunRequest request = GetDetectRunRequest.builder().runId("run-123").build(); - + public void apiErrorsOnInheritedMethodsMapToSkyflowException() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - DeidentifyFileResponse response = controller.getDetectRun(request); - Assert.assertNotNull(response); - Assert.assertEquals("run-123", response.getRunId()); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); + server.enqueue(new MockResponse().setResponseCode(404).setHeader("x-request-id", "req-404") + .setBody("{\"error\":{\"grpc_code\":5,\"http_code\":404,\"message\":\"run not found\",\"http_status\":\"Not Found\",\"details\":[]}}")); + try { + controllerFor(server).getRun(GetRunRequest.builder().runId("missing").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(404, e.getHttpCode()); + Assert.assertEquals("run not found", e.getMessage()); + Assert.assertEquals("req-404", e.getRequestId()); + Assert.assertEquals(Integer.valueOf(5), e.getGrpcCode()); + } + } finally { + server.shutdown(); } } - // ─── getDetectRun — API error path ──────────────────────────────────────── - - @Test - public void testGetDetectRunApiError() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - - int expectedStatusCode = 404; - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class))) - .thenThrow(new ApiClientApiException("Not Found", expectedStatusCode, "run not found")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - GetDetectRunRequest request = GetDetectRunRequest.builder().runId("run-999").build(); - - try { - controller.getDetectRun(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(expectedStatusCode, e.getHttpCode()); + // ─── reidentifyFile (shared, inherited from BaseDetectController) ───────── + + @Test + public void reidentifyFileValidatesBeforeResolvingCredentials() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), (Credentials) null); + ReidentifyFileRequest[] bad = { + null, + ReidentifyFileRequest.builder().value("Zm9v").build(), + ReidentifyFileRequest.builder().dataSource(DataSourceType.BASE64).value(" ").build(), + }; + BaseErrorMessage[] expected = { + BaseErrorMessage.ReidentifyFileRequestNull, + BaseErrorMessage.InvalidDataSourceInReidentifyFile, + BaseErrorMessage.InvalidValueInReidentifyFile, + }; + for (int i = 0; i < bad.length; i++) { + try { + controller.reidentifyFile(bad[i]); + Assert.fail("expected SkyflowException for case " + i); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(expected[i].getMessage(), e.getMessage()); + } } } @Test - public void testGetDetectRunApiClientException() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class))) - .thenThrow(new ApiClientException("Network error executing HTTP request")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - GetDetectRunRequest request = GetDetectRunRequest.builder().runId("run-abc").build(); - + public void reidentifyFileMissingCredentialsSurfaceWithoutNetworkCall() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), emptyCredentials()); try { - controller.getDetectRun(request); - Assert.fail(EXCEPTION_NOT_THROWN); + controller.reidentifyFile(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v").build()); + Assert.fail("expected SkyflowException"); } catch (SkyflowException e) { - Assert.assertTrue(e.getCause() instanceof ApiClientException); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); } } @Test - public void testDeidentifyFilePollingApiClientException() throws Exception { - // Covers pollForResults' own catch(ApiClientException) — the network-error path hit while - // polling getRun, as opposed to the request-time ApiClientApiException covered elsewhere - // (see the sibling ApiClientApiException test above). deidentifyFile's own - // catch (Exception ex) around the pollForResults() call re-wraps whatever it throws into a - // fixed PollingForResultsFailed SkyflowException, so that — not the original cause — is - // what actually surfaces here; pollForResults' catch(ApiClientException) still executes - // (and is covered) on the way there. - File tmpFile = File.createTempFile("test-detect", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content for txt".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-123").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenThrow(new ApiClientException("Network error executing HTTP request")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()) - .build(); - + public void reidentifyFileSendsScopedRequestAndMapsResponse() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - controller.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.PollingForResultsFailed.getMessage(), e.getMessage()); + server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") + .setBody("{\"status\":\"SUCCESS\",\"outputType\":\"BASE64\"," + + "\"output\":[{\"processedFile\":\"SGVsbG8=\",\"processedFileType\":\"REIDENTIFIED_FILE\"," + + "\"processedFileExtension\":\"txt\"}]," + + "\"metrics\":{\"size\":0.5,\"wordCount\":3,\"characterCount\":12}}")); + + ReidentifyFileResponse response = controllerFor(server).reidentifyFile(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64) + .value("W05BTUVfMV0=") + .dataFormat(FileDataFormat.TXT) + .redactionLevel(Arrays.asList( + RedactionLevel.builder().tokenGroupName("names").redactionPattern("mask").build())) + .build()); + + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(DataSourceType.BASE64, response.getOutputType()); + Assert.assertEquals(1, response.getOutput().size()); + Assert.assertEquals("SGVsbG8=", response.getOutput().get(0).getProcessedFile()); + Assert.assertEquals("REIDENTIFIED_FILE", response.getOutput().get(0).getProcessedFileType()); + Assert.assertEquals(FileDataFormat.TXT, response.getOutput().get(0).getProcessedFileExtension()); + Assert.assertEquals(Integer.valueOf(3), response.getMetrics().getWordCount()); + + RecordedRequest recorded = server.takeRequest(); + Assert.assertEquals("POST", recorded.getMethod()); + Assert.assertEquals("/v2/detect/reidentify/file", recorded.getPath()); + Assert.assertEquals("Bearer sky-abcde-0123456789abcdef0123456789abcdef", recorded.getHeader("Authorization")); + Assert.assertNotNull(recorded.getHeader("sky-metadata")); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"dataSource\":\"BASE64\"")); + Assert.assertTrue(body, body.contains("\"value\":\"W05BTUVfMV0=\"")); + Assert.assertTrue(body, body.contains("\"vaultId\":\"vault-1\"")); + Assert.assertTrue(body, body.contains("\"dataFormat\":\"txt\"")); + Assert.assertTrue(body, body.contains("\"tokenGroupName\":\"names\"")); + Assert.assertTrue(body, body.contains("\"redactionPattern\":\"mask\"")); + } finally { + server.shutdown(); } } - // ─── helpers ───────────────────────────────────────────────────────────── - - private static DetectRunsResponse buildSuccessDetectRunsResponse() { - return DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.SUCCESS) - .outputType(DetectRunsResponseOutputType.BASE_64) - .size(1.0f) - .duration(0.5f) - .build(); - } - - private DeidentifyFileResponse runDeidentifyFileForExtension( - String extension, FilesClient mockFilesClient) throws Exception { - return runDeidentifyFileForExtension(extension, mockFilesClient, null); - } - - private DeidentifyFileResponse runDeidentifyFileForExtension( - String extension, FilesClient mockFilesClient, TokenFormat tokenFormat) throws Exception { - File tmpFile = File.createTempFile("test-detect", "." + extension); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), ("content for " + extension).getBytes()); - - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(buildSuccessDetectRunsResponse()); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest.DeidentifyFileRequestBuilder builder = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()); - if (tokenFormat != null) { - builder.tokenFormat(tokenFormat); - } - return controller.deidentifyFile(builder.build()); - } - @Test - public void testGetDetectRunApiError500() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - - int expectedStatusCode = 500; - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class))) - .thenThrow(new ApiClientApiException("Internal Server Error", expectedStatusCode, "internal error body")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - GetDetectRunRequest request = GetDetectRunRequest.builder().runId("run-abc").build(); - + public void reidentifyFileToleratesSparseAndUnknownResponseValues() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - controller.getDetectRun(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(expectedStatusCode, e.getHttpCode()); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"SOMETHING_NEW\"}")); + ReidentifyFileResponse response = controllerFor(server).reidentifyFile(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.SKYFLOW_ID).value("rec-1").build()); + Assert.assertEquals(DetectRunStatus.UNKNOWN, response.getStatus()); + Assert.assertNull(response.getOutputType()); + Assert.assertTrue(response.getOutput().isEmpty()); + Assert.assertNull(response.getMetrics()); + String body = server.takeRequest().getBody().readUtf8(); + Assert.assertFalse(body, body.contains("dataFormat")); + Assert.assertFalse(body, body.contains("redactionLevel")); + } finally { + server.shutdown(); } } - // ─── deidentifyFile — validation ────────────────────────────────────────── - @Test - public void testDeidentifyFile_nullRequest() { + public void reidentifyFileMapsApiErrors() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.detect(vaultID).deidentifyFile(null); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyRequestBody.getMessage(), e.getMessage()); + server.enqueue(new MockResponse().setResponseCode(400).setHeader("x-request-id", "req-9") + .setBody("{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"unsupported format\"," + + "\"http_status\":\"Bad Request\",\"details\":[]}}")); + try { + controllerFor(server).reidentifyFile(ReidentifyFileRequest.builder() + .dataSource(DataSourceType.PRESIGNED_URL).value("https://example.com/f").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(400, e.getHttpCode()); + Assert.assertEquals("unsupported format", e.getMessage()); + Assert.assertEquals("req-9", e.getRequestId()); + Assert.assertEquals(Integer.valueOf(3), e.getGrpcCode()); + } + } finally { + server.shutdown(); } } + // ─── deidentifyFile (shared, inherited from BaseDetectController) ───────── + @Test - public void testDeidentifyFile_noFileOrPathProvided() { + public void deidentifyFileValidatesBeforeResolvingCredentials() throws SkyflowException { + DetectController controller = new DetectController(vaultConfig("vault-a"), (Credentials) null); try { - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().build()) - .build(); - skyflowClient.detect(vaultID).deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); + controller.deidentifyFile(DeidentifyFileRequest.builder().value("Zm9v").build()); + Assert.fail("expected SkyflowException"); } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage(), e.getMessage()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(BaseErrorMessage.InvalidDataSourceInDeidentifyFile.getMessage(), e.getMessage()); } } - // ─── deidentifyFile — happy path ────────────────────────────────────────── - - @Test - public void testDeidentifyFile_successWithTxtFileObject() throws Exception { - File tmpFile = File.createTempFile("test-detect", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "hello world".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-txt-001").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(buildSuccessDetectRunsResponse()); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()).build(); - - DeidentifyFileResponse response = controller.deidentifyFile(request); - Assert.assertNotNull(response); - } - - @Test - public void testDeidentifyFile_successWithFilePath() throws Exception { - File tmpFile = File.createTempFile("test-detect-path", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-path-001").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(buildSuccessDetectRunsResponse()); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().filePath(tmpFile.getAbsolutePath()).build()).build(); - - DeidentifyFileResponse response = controller.deidentifyFile(request); - Assert.assertNotNull(response); - } - - @Test - public void testDeidentifyFile_successWithOutputFile() throws Exception { - File tmpFile = File.createTempFile("test-detect-out", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - String b64 = Base64.getEncoder().encodeToString("processed content".getBytes()); - DeidentifiedFileOutput outputItem = DeidentifiedFileOutput.builder() - .processedFile(b64) - .processedFileExtension(DeidentifiedFileOutputProcessedFileExtension.TXT) - .build(); - DetectRunsResponse successWithOutput = DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.SUCCESS) - .outputType(DetectRunsResponseOutputType.BASE_64) - .size(1.0f).duration(0.5f) - .output(Collections.singletonList(outputItem)) - .build(); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-out-001").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(successWithOutput); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()) - .outputDirectory(System.getProperty("java.io.tmpdir")) - .build(); - - DeidentifyFileResponse response = controller.deidentifyFile(request); - Assert.assertNotNull(response); - } - - // ─── deidentifyFile — IN_PROGRESS timeout ───────────────────────────────── - - @Test - public void testDeidentifyFile_inProgressTimeout() throws Exception { - File tmpFile = File.createTempFile("test-detect-prog", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-prog-001").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(DetectRunsResponse.builder().status(DetectRunsResponseStatus.IN_PROGRESS).build()); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()) - .waitTime(1) - .build(); - - DeidentifyFileResponse response = controller.deidentifyFile(request); - Assert.assertNotNull(response); - Assert.assertEquals("IN_PROGRESS", response.getStatus()); - } - - // ─── deidentifyFile — error paths ───────────────────────────────────────── - @Test - public void testDeidentifyFile_nonExistentFilePath() { + public void deidentifyFileSubmitOnlyReturnsRunIdWithoutPolling() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - DetectController controller = createDetectControllerWithMock(Mockito.mock(ApiClient.class)); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().filePath("/nonexistent/path/file.txt").build()) - .build(); - controller.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { - Assert.assertNotNull(e.getMessage()); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"runId\":\"run-42\"}")); + + DeidentifyFileResponse response = controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.SKYFLOW_ID).value("rec-1").dataFormat(FileDataFormat.PDF) + .configurationId("cfg-1").build()); + + Assert.assertEquals("run-42", response.getRunId()); + Assert.assertNull(response.getStatus()); + Assert.assertTrue(response.getOutput().isEmpty()); + + RecordedRequest recorded = server.takeRequest(); + assertCommonHeaders(recorded, "POST", "/v2/detect/deidentify/file"); + String body = recorded.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"dataSource\":\"SKYFLOW_ID\"")); + Assert.assertTrue(body, body.contains("\"value\":\"rec-1\"")); + Assert.assertTrue(body, body.contains("\"dataFormat\":\"pdf\"")); + Assert.assertTrue(body, body.contains("\"configurationId\":\"cfg-1\"")); + Assert.assertEquals("only the submit call was made", 1, server.getRequestCount()); + } finally { + server.shutdown(); } } @Test - public void testDeidentifyFile_processFileApiError() throws Exception { - File tmpFile = File.createTempFile("test-detect-err", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())) - .thenThrow(new ApiClientApiException("forbidden", 403, "access denied")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()).build(); + public void deidentifyFilePollsToSuccessAndWritesOutputsForLocalFile() throws Exception { + File input = folder.newFile("invoice.txt"); + Files.write(input.toPath(), "Pay John Doe".getBytes("UTF-8")); + File outDir = folder.newFolder("out"); + String redacted = Base64.getEncoder().encodeToString("Pay [NAME_1]".getBytes("UTF-8")); + MockWebServer server = new MockWebServer(); + server.start(); try { - controller.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(403, e.getHttpCode()); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"runId\":\"run-7\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"QUEUED\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"SUCCESS\",\"outputType\":\"BASE64\"," + + "\"output\":[{\"processedFile\":\"" + redacted + "\",\"processedFileType\":\"REDACTED_FILE\",\"processedFileExtension\":\"txt\"}," + + "{\"processedFile\":\"W10=\",\"processedFileType\":\"ENTITIES\",\"processedFileExtension\":\"json\"}]," + + "\"metrics\":{\"wordCount\":3}}")); + + DeidentifyFileResponse response = controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .file(input).configurationId("cfg-1") + .pollOptions(PollOptions.builder().waitTime(1).build()) // one real 1 s sleep at most + .outputDirectory(outDir.getPath()) + .build()); + + Assert.assertEquals("run-7", response.getRunId()); + Assert.assertEquals(DetectRunStatus.SUCCESS, response.getStatus()); + Assert.assertEquals(DataSourceType.BASE64, response.getOutputType()); + Assert.assertEquals(2, response.getOutput().size()); + Assert.assertEquals(Integer.valueOf(3), response.getMetrics().getWordCount()); + Assert.assertEquals("Pay [NAME_1]", new String(Files.readAllBytes(new File(outDir, "processed-invoice.txt").toPath()), "UTF-8")); + Assert.assertEquals("[]", new String(Files.readAllBytes(new File(outDir, "processed-entities-invoice.json").toPath()), "UTF-8")); + + RecordedRequest submit = server.takeRequest(); + assertCommonHeaders(submit, "POST", "/v2/detect/deidentify/file"); + String body = submit.getBody().readUtf8(); + Assert.assertTrue(body, body.contains("\"dataSource\":\"BASE64\"")); + Assert.assertTrue(body, body.contains("\"value\":\"" + Base64.getEncoder().encodeToString("Pay John Doe".getBytes("UTF-8")) + "\"")); + Assert.assertTrue(body, body.contains("\"dataFormat\":\"txt\"")); + Assert.assertEquals("/v2/detect/runs/run-7?vaultId=vault-1", server.takeRequest().getPath()); + Assert.assertEquals("/v2/detect/runs/run-7?vaultId=vault-1", server.takeRequest().getPath()); + } finally { + server.shutdown(); } } @Test - public void testDeidentifyFile_pollForResultsApiError() throws Exception { - File tmpFile = File.createTempFile("test-detect-poll", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-poll-err").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenThrow(new ApiClientApiException("unavailable", 503, "service unavailable")); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()).build(); - + public void deidentifyFileReturnsRunIdWithStatusWhenBudgetRunsOut() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - controller.deidentifyFile(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorMessage.PollingForResultsFailed.getMessage(), e.getMessage()); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"runId\":\"run-8\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"IN_PROGRESS\"}")); + + DeidentifyFileResponse response = controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v") + .pollOptions(PollOptions.builder().maxAttempts(1).build()).build()); + + Assert.assertEquals("run-8", response.getRunId()); + Assert.assertEquals(DetectRunStatus.IN_PROGRESS, response.getStatus()); + Assert.assertTrue(response.getOutput().isEmpty()); + Assert.assertEquals(2, server.getRequestCount()); + } finally { + server.shutdown(); } } - // ─── processFileByType — all extensions ─────────────────────────────────── - - @Test - public void testDeidentifyFile_pdfExtension() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyPdf(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-pdf").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("pdf", mockFilesClient)); - } - - @Test - public void testDeidentifyFile_mp3Extension() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyAudio(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-mp3").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("mp3", mockFilesClient)); - } - - @Test - public void testDeidentifyFile_jpgExtension() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyImage(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-jpg").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("jpg", mockFilesClient)); - } - - @Test - public void testDeidentifyFile_pptExtension() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyPresentation(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-ppt").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("ppt", mockFilesClient)); - } - - @Test - public void testDeidentifyFile_csvExtension() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifySpreadsheet(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-csv").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("csv", mockFilesClient)); - } - - @Test - public void testDeidentifyFile_docExtension() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyDocument(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-doc").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("doc", mockFilesClient)); - } - - @Test - public void testDeidentifyFile_jsonExtension() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyStructuredText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-json").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("json", mockFilesClient)); - } - - @Test - public void testDeidentifyFile_defaultExtension() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyFile(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-dcm").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("dcm", mockFilesClient)); - } - - // ─── parseDeidentifyFileResponse — wordCharacterCount branch L272-273 ───── - @Test - public void testGetDetectRun_withWordCharacterCount() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - - DeidentifiedFileOutput outputItem = DeidentifiedFileOutput.builder().build(); - WordCharacterCount wordCharCount = WordCharacterCount.builder() - .wordCount(10) - .characterCount(55) - .build(); - - DetectRunsResponse fakeRunsResponse = DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.SUCCESS) - .outputType(DetectRunsResponseOutputType.BASE_64) - .size(5.0f) - .duration(0.5f) - .output(Collections.singletonList(outputItem)) - .wordCharacterCount(wordCharCount) - .build(); - - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class))) - .thenReturn(fakeRunsResponse); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - GetDetectRunRequest request = GetDetectRunRequest.builder().runId("run-wc-001").build(); - + public void deidentifyFileSurfacesFailedRunMessage() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - DeidentifyFileResponse response = controller.getDetectRun(request); - Assert.assertNotNull(response); - Assert.assertEquals(10, (int) response.getWordCount()); - Assert.assertEquals(55, (int) response.getCharCount()); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); - } - } - - // ─── deidentifyFile — processedFile present, no outputDirectory (lines 146, 168) ─── - - @Test - public void testDeidentifyFile_successWithProcessedFileNoOutputDir() throws Exception { - File tmpFile = File.createTempFile("test-detect-nodir", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - String b64 = Base64.getEncoder().encodeToString("processed content".getBytes()); - DeidentifiedFileOutput outputItem = DeidentifiedFileOutput.builder() - .processedFile(b64) - .processedFileExtension(DeidentifiedFileOutputProcessedFileExtension.TXT) - .build(); - DetectRunsResponse successWithOutput = DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.SUCCESS) - .outputType(DetectRunsResponseOutputType.BASE_64) - .size(1.0f).duration(0.5f) - .output(Collections.singletonList(outputItem)) - .build(); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-nodir-001").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(successWithOutput); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - // no outputDirectory → file written via new File(outputFileName) (line 146) - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()) - .build(); - - DeidentifyFileResponse response = controller.deidentifyFile(request); - Assert.assertNotNull(response); - } - - // ─── pollForResults — IN_PROGRESS retry then SUCCESS (lines 218-229) ───────── - - @Test - public void testDeidentifyFile_inProgressThenSuccess() throws Exception { - File tmpFile = File.createTempFile("test-detect-retry", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-retry-001").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(DetectRunsResponse.builder().status(DetectRunsResponseStatus.IN_PROGRESS).build()) - .thenReturn(buildSuccessDetectRunsResponse()); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - // waitTime=2: first poll IN_PROGRESS → sleeps 1s → second poll SUCCESS - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()) - .waitTime(2) - .build(); - - DeidentifyFileResponse response = controller.deidentifyFile(request); - Assert.assertNotNull(response); - Assert.assertFalse("IN_PROGRESS".equals(response.getStatus())); - } - - // ─── pollForResults — IN_PROGRESS retry (else branch, lines 225-226) ──────── - - @Test - public void testDeidentifyFile_inProgressElseBranchThenSuccess() throws Exception { - File tmpFile = File.createTempFile("test-detect-else", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-else-001").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(DetectRunsResponse.builder().status(DetectRunsResponseStatus.IN_PROGRESS).build()) - .thenReturn(buildSuccessDetectRunsResponse()); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - // waitTime=3: currentWaitTime=1, nextWaitTime=2 < 3 → else branch (L225-226), sleep 2s - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()) - .waitTime(3) - .build(); - - DeidentifyFileResponse response = controller.deidentifyFile(request); - Assert.assertNotNull(response); - } + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"runId\":\"run-9\"}")); + server.enqueue(new MockResponse().setResponseCode(200).setBody("{\"status\":\"FAILED\",\"message\":\"unsupported file\"}")); - // ─── parseDeidentifyFileResponse — processedFile present branch L283-291 ── + DeidentifyFileResponse response = controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v").pollOptions(PollOptions.builder().build()).build()); - @Test - public void testGetDetectRun_withProcessedFile() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - - String base64Content = Base64.getEncoder().encodeToString("test file content".getBytes()); - DeidentifiedFileOutput outputItem = DeidentifiedFileOutput.builder() - .processedFile(base64Content) - .processedFileExtension(DeidentifiedFileOutputProcessedFileExtension.TXT) - .build(); - - DetectRunsResponse fakeRunsResponse = DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.SUCCESS) - .outputType(DetectRunsResponseOutputType.BASE_64) - .size(1.0f) - .duration(0.1f) - .output(Collections.singletonList(outputItem)) - .build(); - - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class))) - .thenReturn(fakeRunsResponse); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - GetDetectRunRequest request = GetDetectRunRequest.builder().runId("run-file-001").build(); - - try { - DeidentifyFileResponse response = controller.getDetectRun(request); - Assert.assertNotNull(response); - Assert.assertEquals("run-file-001", response.getRunId()); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); + Assert.assertEquals(DetectRunStatus.FAILED, response.getStatus()); + Assert.assertEquals("unsupported file", response.getMessage()); + Assert.assertEquals(2, server.getRequestCount()); + } finally { + server.shutdown(); } } - // ─── entityUniqueCounter branches in VaultClient request builders ───────── - - private static TokenFormat buildEntityUniqueCounterTokenFormat() { - return TokenFormat.builder() - .entityUniqueCounter(java.util.Collections.singletonList(DetectEntities.EMAIL_ADDRESS)) - .build(); - } - - @Test - public void testDeidentifyFile_txt_withEntityUniqueCounter() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-euc-txt").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("txt", mockFilesClient, buildEntityUniqueCounterTokenFormat())); - } - - @Test - public void testDeidentifyFile_mp3_withEntityUniqueCounter() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyAudio(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-euc-mp3").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("mp3", mockFilesClient, buildEntityUniqueCounterTokenFormat())); - } - - @Test - public void testDeidentifyFile_pdf_withEntityUniqueCounter() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyPdf(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-euc-pdf").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("pdf", mockFilesClient, buildEntityUniqueCounterTokenFormat())); - } - - @Test - public void testDeidentifyFile_jpg_withEntityUniqueCounter() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyImage(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-euc-jpg").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("jpg", mockFilesClient, buildEntityUniqueCounterTokenFormat())); - } - - @Test - public void testDeidentifyFile_csv_withEntityUniqueCounter() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifySpreadsheet(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-euc-csv").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("csv", mockFilesClient, buildEntityUniqueCounterTokenFormat())); - } - - @Test - public void testDeidentifyFile_dcm_withEntityUniqueCounter() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - when(mockFilesClient.deidentifyFile(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-euc-dcm").build()); - Assert.assertNotNull(runDeidentifyFileForExtension("dcm", mockFilesClient, buildEntityUniqueCounterTokenFormat())); - } - - // --- unsupported file extension must throw SkyflowException, not IllegalArgumentException --- - @Test - public void testDeidentifyFile_unsupportedExtensionThrowsSkyflowException() throws Exception { - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); + public void deidentifyFileSubmitErrorMapsToSkyflowException() throws Exception { + MockWebServer server = new MockWebServer(); + server.start(); try { - runDeidentifyFileForExtension("xyz", mockFilesClient); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertNotNull(e.getMessage()); + server.enqueue(new MockResponse().setResponseCode(400).setHeader("x-request-id", "req-1") + .setBody("{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"configuration not found\",\"http_status\":\"Bad Request\",\"details\":[]}}")); + try { + controllerFor(server).deidentifyFile(DeidentifyFileRequest.builder() + .dataSource(DataSourceType.BASE64).value("Zm9v").configurationId("missing").build()); + Assert.fail("expected SkyflowException"); + } catch (SkyflowException e) { + Assert.assertEquals(400, e.getHttpCode()); + Assert.assertEquals("configuration not found", e.getMessage()); + Assert.assertEquals("req-1", e.getRequestId()); + } + } finally { + server.shutdown(); } } - - // --- getEntities — output present but empty list must return empty list, not throw --- - - @Test - public void testGetEntities_emptyOutputListReturnsEmptyList() throws Exception { - DetectRunsResponse response = DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.SUCCESS) - .output(Collections.emptyList()) - .build(); - - java.lang.reflect.Method method = DetectController.class.getDeclaredMethod("getEntities", DetectRunsResponse.class); - method.setAccessible(true); - java.util.List result = (java.util.List) method.invoke(null, response); - - Assert.assertNotNull(result); - Assert.assertTrue("entities should be empty when output list is empty", result.isEmpty()); - } - - // --- parseDeidentifyFileResponse — FAILED run with absent optional fields must not throw --- - - @Test - public void testParseDeidentifyFileResponse_failedRunWithAbsentFieldsDoesNotThrow() throws Exception { - DetectRunsResponse response = DetectRunsResponse.builder() - .status(DetectRunsResponseStatus.FAILED) - .build(); - - java.lang.reflect.Method method = DetectController.class.getDeclaredMethod( - "parseDeidentifyFileResponse", DetectRunsResponse.class, String.class, String.class); - method.setAccessible(true); - DeidentifyFileResponse result = (DeidentifyFileResponse) method.invoke( - null, response, "run-failed-001", DetectRunsResponseStatus.FAILED.toString()); - - Assert.assertNotNull(result); - Assert.assertEquals("run-failed-001", result.getRunId()); - } - - // --- getBaseFileName — filename with no extension must not throw StringIndexOutOfBoundsException --- - - @Test - public void testGetBaseFileName_withExtensionStripsIt() throws Exception { - java.lang.reflect.Method method = DetectController.class.getDeclaredMethod("getBaseFileName", String.class); - method.setAccessible(true); - DetectController controller = createDetectControllerWithMock(Mockito.mock(ApiClient.class)); - String result = (String) method.invoke(controller, "photo.png"); - Assert.assertEquals("photo", result); - } - - @Test - public void testGetBaseFileName_withoutExtensionReturnsWholeName() throws Exception { - java.lang.reflect.Method method = DetectController.class.getDeclaredMethod("getBaseFileName", String.class); - method.setAccessible(true); - DetectController controller = createDetectControllerWithMock(Mockito.mock(ApiClient.class)); - String result = (String) method.invoke(controller, "noextension"); - Assert.assertEquals("noextension", result); - } - - // --- pollForResults — one poll response with absent status must not throw; loop continues --- - - @Test - public void testDeidentifyFile_pollAbsentStatusThenSuccess() throws Exception { - File tmpFile = File.createTempFile("test-detect-absentstatus", ".txt"); - tmpFile.deleteOnExit(); - Files.write(tmpFile.toPath(), "content".getBytes()); - - FilesClient mockFilesClient = Mockito.mock(FilesClient.class); - ApiClient mockApiClient = Mockito.mock(ApiClient.class); - when(mockApiClient.files()).thenReturn(mockFilesClient); - when(mockFilesClient.deidentifyText(any())).thenReturn( - com.skyflow.generated.rest.types.DeidentifyFileResponse.builder().runId("run-absent-status").build()); - when(mockFilesClient.getRun(anyString(), any(GetRunRequest.class), any(RequestOptions.class))) - .thenReturn(DetectRunsResponse.builder().build()) - .thenReturn(buildSuccessDetectRunsResponse()); - - DetectController controller = createDetectControllerWithMock(mockApiClient); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(FileInput.builder().file(tmpFile).build()) - .build(); - - DeidentifyFileResponse response = controller.deidentifyFile(request); - Assert.assertNotNull(response); - } } diff --git a/skyvault/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/skyvault/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java index 8cae2235..4636dd6d 100644 --- a/skyvault/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java +++ b/skyvault/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -20,19 +20,6 @@ import com.skyflow.generated.rest.resources.records.RecordsClient; import com.skyflow.generated.rest.resources.tokens.RawTokensClient; import com.skyflow.generated.rest.resources.tokens.TokensClient; -import com.skyflow.generated.rest.types.UploadFileV2Response; -import com.skyflow.generated.rest.types.V1BatchOperationResponse; -import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; -import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; -import com.skyflow.generated.rest.types.V1DetokenizeRecordResponse; -import com.skyflow.generated.rest.types.V1DetokenizeResponse; -import com.skyflow.generated.rest.types.V1FieldRecords; -import com.skyflow.generated.rest.types.V1GetQueryResponse; -import com.skyflow.generated.rest.types.V1InsertRecordResponse; -import com.skyflow.generated.rest.types.V1RecordMetaProperties; -import com.skyflow.generated.rest.types.V1TokenizeRecordResponse; -import com.skyflow.generated.rest.types.V1TokenizeResponse; -import com.skyflow.generated.rest.types.V1UpdateRecordResponse; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.vault.data.DeleteRequest; @@ -74,6 +61,18 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; +import com.skyflow.generated.rest.types.UploadFileResponseV2; +import com.skyflow.generated.rest.types.UpdateRecordResponse; +import com.skyflow.generated.rest.types.TokenizeRecordResponse; +import com.skyflow.generated.rest.types.RecordMetaProperties; +import com.skyflow.generated.rest.types.InsertRecordResponse; +import com.skyflow.generated.rest.types.GetQueryResponse; +import com.skyflow.generated.rest.types.GetFieldRecords; +import com.skyflow.generated.rest.types.FieldRecords; +import com.skyflow.generated.rest.types.BulkGetRecordResponse; +import com.skyflow.generated.rest.types.BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.BatchOperationResponse; +import com.skyflow.generated.rest.resources.files.FilesClient; public class VaultControllerTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; @@ -275,9 +274,9 @@ public void testGetFormattedGetRecordNormalisesSkyflowId() throws Exception { Map fields = new HashMap<>(); fields.put("skyflow_id", "abc-123"); fields.put("name", "John"); - V1FieldRecords record = V1FieldRecords.builder().fields(fields).build(); + GetFieldRecords record = GetFieldRecords.builder().fields(fields).build(); - Method method = VaultController.class.getDeclaredMethod("getFormattedGetRecord", V1FieldRecords.class); + Method method = VaultController.class.getDeclaredMethod("getFormattedGetRecord", GetFieldRecords.class); method.setAccessible(true); @SuppressWarnings("unchecked") HashMap result = (HashMap) method.invoke(null, record); @@ -292,9 +291,9 @@ public void testGetFormattedQueryRecordNormalisesSkyflowId() throws Exception { Map fields = new HashMap<>(); fields.put("skyflow_id", "xyz-456"); fields.put("email", "test@example.com"); - V1FieldRecords record = V1FieldRecords.builder().fields(fields).build(); + FieldRecords record = FieldRecords.builder().fields(fields).build(); - Method method = VaultController.class.getDeclaredMethod("getFormattedQueryRecord", V1FieldRecords.class); + Method method = VaultController.class.getDeclaredMethod("getFormattedQueryRecord", FieldRecords.class); method.setAccessible(true); @SuppressWarnings("unchecked") HashMap result = (HashMap) method.invoke(null, record); @@ -309,9 +308,9 @@ public void testGetFormattedGetRecordNormalisesSkyflowIdInTokensBranch() throws Map tokens = new HashMap<>(); tokens.put("skyflow_id", "tok-789"); tokens.put("card_number", "tok-card-abc"); - V1FieldRecords record = V1FieldRecords.builder().tokens(tokens).build(); + GetFieldRecords record = GetFieldRecords.builder().tokens(tokens).build(); - Method method = VaultController.class.getDeclaredMethod("getFormattedGetRecord", V1FieldRecords.class); + Method method = VaultController.class.getDeclaredMethod("getFormattedGetRecord", GetFieldRecords.class); method.setAccessible(true); @SuppressWarnings("unchecked") HashMap result = (HashMap) method.invoke(null, record); @@ -443,11 +442,11 @@ public void testInsert_bulkSuccess() throws Exception { RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - V1RecordMetaProperties meta = V1RecordMetaProperties.builder().skyflowId("id-123").build(); - V1InsertRecordResponse insertResp = V1InsertRecordResponse.builder() + RecordMetaProperties meta = RecordMetaProperties.builder().skyflowId("id-123").build(); + InsertRecordResponse insertResp = InsertRecordResponse.builder() .records(Collections.singletonList(meta)) .build(); - when(mockRecords.recordServiceInsertRecord(anyString(), anyString(), any())).thenReturn(insertResp); + when(mockRecords.insertRecords(anyString(), anyString(), any())).thenReturn(insertResp); VaultController controller = createControllerWithMock(mockApi); @@ -470,7 +469,7 @@ public void testInsert_bulkApiErrorThrowsSkyflowException() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceInsertRecord(anyString(), anyString(), any())) + when(mockRecords.insertRecords(anyString(), anyString(), any())) .thenThrow(new ApiClientApiException("insert failed", 400, "bad request body")); VaultController controller = createControllerWithMock(mockApi); @@ -496,7 +495,7 @@ public void testInsert_apiClientExceptionThrowsSkyflowException() throws Excepti ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceInsertRecord(anyString(), anyString(), any())) + when(mockRecords.insertRecords(anyString(), anyString(), any())) .thenThrow(new ApiClientException("Network error executing HTTP request")); VaultController controller = createControllerWithMock(mockApi); @@ -525,10 +524,10 @@ public void testInsert_batchSuccess() throws Exception { when(mockApi.records()).thenReturn(mockRecords); when(mockRecords.withRawResponse()).thenReturn(mockRawRecords); - V1BatchOperationResponse batchBody = V1BatchOperationResponse.builder().build(); + BatchOperationResponse batchBody = BatchOperationResponse.builder().build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); - when(mockRawRecords.recordServiceBatchOperation(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); + when(mockRawRecords.batchOperation(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -553,7 +552,7 @@ public void testInsert_batchApiErrorThrowsSkyflowException() throws Exception { RawRecordsClient mockRawRecords = Mockito.mock(RawRecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); when(mockRecords.withRawResponse()).thenReturn(mockRawRecords); - when(mockRawRecords.recordServiceBatchOperation(anyString(), any(), any())) + when(mockRawRecords.batchOperation(anyString(), any(), any())) .thenThrow(new ApiClientApiException("batch failed", 500, "server error")); VaultController controller = createControllerWithMock(mockApi); @@ -586,15 +585,15 @@ public void testDetokenize_success() throws Exception { when(mockApi.tokens()).thenReturn(mockTokens); when(mockTokens.withRawResponse()).thenReturn(mockRawTokens); - V1DetokenizeRecordResponse detokRecord = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse detokRecord = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("tok-123") .build(); - V1DetokenizeResponse detokBody = V1DetokenizeResponse.builder() + com.skyflow.generated.rest.types.DetokenizeResponse detokBody = com.skyflow.generated.rest.types.DetokenizeResponse.builder() .records(Collections.singletonList(detokRecord)) .build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); - when(mockRawTokens.recordServiceDetokenize(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); + when(mockRawTokens.detokenize(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -617,7 +616,7 @@ public void testDetokenize_apiErrorThrowsSkyflowException() throws Exception { RawTokensClient mockRawTokens = Mockito.mock(RawTokensClient.class); when(mockApi.tokens()).thenReturn(mockTokens); when(mockTokens.withRawResponse()).thenReturn(mockRawTokens); - when(mockRawTokens.recordServiceDetokenize(anyString(), any(), any())) + when(mockRawTokens.detokenize(anyString(), any(), any())) .thenThrow(new ApiClientApiException("detokenize failed", 401, "unauthorized")); VaultController controller = createControllerWithMock(mockApi); @@ -643,7 +642,7 @@ public void testDetokenize_apiClientExceptionThrowsSkyflowException() throws Exc RawTokensClient mockRawTokens = Mockito.mock(RawTokensClient.class); when(mockApi.tokens()).thenReturn(mockTokens); when(mockTokens.withRawResponse()).thenReturn(mockRawTokens); - when(mockRawTokens.recordServiceDetokenize(anyString(), any(), any())) + when(mockRawTokens.detokenize(anyString(), any(), any())) .thenThrow(new ApiClientException("Network error executing HTTP request")); VaultController controller = createControllerWithMock(mockApi); @@ -673,11 +672,11 @@ public void testGet_success() throws Exception { Map fields = new HashMap<>(); fields.put("skyflow_id", "id-get-001"); fields.put("card_number", "4111111111111111"); - V1FieldRecords fieldRecords = V1FieldRecords.builder().fields(fields).build(); - V1BulkGetRecordResponse getResp = V1BulkGetRecordResponse.builder() + GetFieldRecords fieldRecords = GetFieldRecords.builder().fields(fields).build(); + BulkGetRecordResponse getResp = BulkGetRecordResponse.builder() .records(Collections.singletonList(fieldRecords)) .build(); - when(mockRecords.recordServiceBulkGetRecord(anyString(), anyString(), any(), any())).thenReturn(getResp); + when(mockRecords.getRecords(anyString(), anyString(), any(), any())).thenReturn(getResp); VaultController controller = createControllerWithMock(mockApi); @@ -697,7 +696,7 @@ public void testGet_apiErrorThrowsSkyflowException() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceBulkGetRecord(anyString(), anyString(), any(), any())) + when(mockRecords.getRecords(anyString(), anyString(), any(), any())) .thenThrow(new ApiClientApiException("get failed", 404, "not found")); VaultController controller = createControllerWithMock(mockApi); @@ -719,7 +718,7 @@ public void testGet_apiClientExceptionThrowsSkyflowException() throws Exception ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceBulkGetRecord(anyString(), anyString(), any(), any())) + when(mockRecords.getRecords(anyString(), anyString(), any(), any())) .thenThrow(new ApiClientException("Network error executing HTTP request")); VaultController controller = createControllerWithMock(mockApi); @@ -744,8 +743,8 @@ public void testUpdate_success() throws Exception { RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - V1UpdateRecordResponse updateResp = V1UpdateRecordResponse.builder().skyflowId("id-upd-001").build(); - when(mockRecords.recordServiceUpdateRecord(anyString(), anyString(), anyString(), any(), any())) + UpdateRecordResponse updateResp = UpdateRecordResponse.builder().skyflowId("id-upd-001").build(); + when(mockRecords.updateRecord(anyString(), anyString(), anyString(), any(), any())) .thenReturn(updateResp); VaultController controller = createControllerWithMock(mockApi); @@ -764,7 +763,7 @@ public void testUpdate_apiErrorThrowsSkyflowException() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceUpdateRecord(anyString(), anyString(), anyString(), any(), any())) + when(mockRecords.updateRecord(anyString(), anyString(), anyString(), any(), any())) .thenThrow(new ApiClientApiException("update failed", 403, "forbidden")); VaultController controller = createControllerWithMock(mockApi); @@ -787,7 +786,7 @@ public void testUpdate_apiClientExceptionThrowsSkyflowException() throws Excepti ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceUpdateRecord(anyString(), anyString(), anyString(), any(), any())) + when(mockRecords.updateRecord(anyString(), anyString(), anyString(), any(), any())) .thenThrow(new ApiClientException("Network error executing HTTP request")); VaultController controller = createControllerWithMock(mockApi); @@ -813,10 +812,10 @@ public void testDelete_success() throws Exception { RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - V1BulkDeleteRecordResponse deleteResp = V1BulkDeleteRecordResponse.builder() + BulkDeleteRecordResponse deleteResp = BulkDeleteRecordResponse.builder() .recordIdResponse(Collections.singletonList("id-del-001")) .build(); - when(mockRecords.recordServiceBulkDeleteRecord(anyString(), anyString(), any(), any())) + when(mockRecords.deleteRecords(anyString(), anyString(), any(), any())) .thenReturn(deleteResp); VaultController controller = createControllerWithMock(mockApi); @@ -837,7 +836,7 @@ public void testDelete_apiErrorThrowsSkyflowException() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceBulkDeleteRecord(anyString(), anyString(), any(), any())) + when(mockRecords.deleteRecords(anyString(), anyString(), any(), any())) .thenThrow(new ApiClientApiException("delete failed", 400, "bad id")); VaultController controller = createControllerWithMock(mockApi); @@ -859,7 +858,7 @@ public void testDelete_apiClientExceptionThrowsSkyflowException() throws Excepti ApiClient mockApi = Mockito.mock(ApiClient.class); RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.recordServiceBulkDeleteRecord(anyString(), anyString(), any(), any())) + when(mockRecords.deleteRecords(anyString(), anyString(), any(), any())) .thenThrow(new ApiClientException("Network error executing HTTP request")); VaultController controller = createControllerWithMock(mockApi); @@ -886,11 +885,11 @@ public void testQuery_success() throws Exception { Map fields = new HashMap<>(); fields.put("skyflow_id", "id-qry-001"); - V1FieldRecords fieldRecords = V1FieldRecords.builder().fields(fields).build(); - V1GetQueryResponse queryResp = V1GetQueryResponse.builder() + FieldRecords fieldRecords = FieldRecords.builder().fields(fields).build(); + GetQueryResponse queryResp = GetQueryResponse.builder() .records(Collections.singletonList(fieldRecords)) .build(); - when(mockQuery.queryServiceExecuteQuery(anyString(), any(), any())).thenReturn(queryResp); + when(mockQuery.executeQuery(anyString(), any(), any())).thenReturn(queryResp); VaultController controller = createControllerWithMock(mockApi); @@ -908,7 +907,7 @@ public void testQuery_apiErrorThrowsSkyflowException() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); QueryClient mockQuery = Mockito.mock(QueryClient.class); when(mockApi.query()).thenReturn(mockQuery); - when(mockQuery.queryServiceExecuteQuery(anyString(), any(), any())) + when(mockQuery.executeQuery(anyString(), any(), any())) .thenThrow(new ApiClientApiException("query failed", 400, "invalid sql")); VaultController controller = createControllerWithMock(mockApi); @@ -928,7 +927,7 @@ public void testQuery_apiClientExceptionThrowsSkyflowException() throws Exceptio ApiClient mockApi = Mockito.mock(ApiClient.class); QueryClient mockQuery = Mockito.mock(QueryClient.class); when(mockApi.query()).thenReturn(mockQuery); - when(mockQuery.queryServiceExecuteQuery(anyString(), any(), any())) + when(mockQuery.executeQuery(anyString(), any(), any())) .thenThrow(new ApiClientException("Network error executing HTTP request")); VaultController controller = createControllerWithMock(mockApi); @@ -973,12 +972,12 @@ public void testInsert_batchSuccessWithRecords() throws Exception { List> responses = new ArrayList<>(); responses.add(responseItem); - V1BatchOperationResponse batchBody = V1BatchOperationResponse.builder() + BatchOperationResponse batchBody = BatchOperationResponse.builder() .responses(responses) .build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); - when(mockRawRecords.recordServiceBatchOperation(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); + when(mockRawRecords.batchOperation(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -1009,14 +1008,14 @@ public void testInsert_bulkSuccessWithTokens() throws Exception { Map tokens = new HashMap<>(); tokens.put("card_number", "tok-card-456"); - V1RecordMetaProperties meta = V1RecordMetaProperties.builder() + RecordMetaProperties meta = RecordMetaProperties.builder() .skyflowId("id-with-tokens") .tokens(tokens) .build(); - V1InsertRecordResponse insertResp = V1InsertRecordResponse.builder() + InsertRecordResponse insertResp = InsertRecordResponse.builder() .records(Collections.singletonList(meta)) .build(); - when(mockRecords.recordServiceInsertRecord(anyString(), anyString(), any())).thenReturn(insertResp); + when(mockRecords.insertRecords(anyString(), anyString(), any())).thenReturn(insertResp); VaultController controller = createControllerWithMock(mockApi); @@ -1044,11 +1043,11 @@ public void testUpdate_withTokensInResponse() throws Exception { Map tokens = new HashMap<>(); tokens.put("card_number", "tok-upd-card"); - V1UpdateRecordResponse updateResp = V1UpdateRecordResponse.builder() + UpdateRecordResponse updateResp = UpdateRecordResponse.builder() .skyflowId("id-upd-tok") .tokens(tokens) .build(); - when(mockRecords.recordServiceUpdateRecord(anyString(), anyString(), anyString(), any(), any())) + when(mockRecords.updateRecord(anyString(), anyString(), anyString(), any(), any())) .thenReturn(updateResp); VaultController controller = createControllerWithMock(mockApi); @@ -1076,16 +1075,16 @@ public void testDetokenize_errorRecordPath() throws Exception { when(mockApi.tokens()).thenReturn(mockTokens); when(mockTokens.withRawResponse()).thenReturn(mockRawTokens); - V1DetokenizeRecordResponse errRecord = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse errRecord = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("tok-bad") .error("token not found") .build(); - V1DetokenizeResponse detokBody = V1DetokenizeResponse.builder() + com.skyflow.generated.rest.types.DetokenizeResponse detokBody = com.skyflow.generated.rest.types.DetokenizeResponse.builder() .records(Collections.singletonList(errRecord)) .build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); - when(mockRawTokens.recordServiceDetokenize(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); + when(mockRawTokens.detokenize(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -1122,12 +1121,12 @@ public void testInsert_batchItemWithDeprecatedSkyflowId() throws Exception { Map responseItem = new HashMap<>(); responseItem.put("Body", bodyMap); - V1BatchOperationResponse batchBody = V1BatchOperationResponse.builder() + BatchOperationResponse batchBody = BatchOperationResponse.builder() .responses(Collections.singletonList(responseItem)) .build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); - when(mockRawRecords.recordServiceBatchOperation(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); + when(mockRawRecords.batchOperation(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -1166,12 +1165,12 @@ public void testInsert_batchMixedResult() throws Exception { Map errorItem = new HashMap<>(); errorItem.put("Body", errorBody); - V1BatchOperationResponse batchBody = V1BatchOperationResponse.builder() + BatchOperationResponse batchBody = BatchOperationResponse.builder() .responses(Arrays.asList(successItem, errorItem)) .build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); - when(mockRawRecords.recordServiceBatchOperation(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); + when(mockRawRecords.batchOperation(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -1208,12 +1207,12 @@ public void testInsert_batchAllErrors() throws Exception { Map errorItem = new HashMap<>(); errorItem.put("Body", errorBody); - V1BatchOperationResponse batchBody = V1BatchOperationResponse.builder() + BatchOperationResponse batchBody = BatchOperationResponse.builder() .responses(Collections.singletonList(errorItem)) .build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); - when(mockRawRecords.recordServiceBatchOperation(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(batchBody, rawResp); + when(mockRawRecords.batchOperation(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -1241,12 +1240,12 @@ public void testDetokenize_emptyRecordsList() throws Exception { when(mockApi.tokens()).thenReturn(mockTokens); when(mockTokens.withRawResponse()).thenReturn(mockRawTokens); - V1DetokenizeResponse detokBody = V1DetokenizeResponse.builder() - .records(Collections.emptyList()) + com.skyflow.generated.rest.types.DetokenizeResponse detokBody = com.skyflow.generated.rest.types.DetokenizeResponse.builder() + .records(Collections.emptyList()) .build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); - when(mockRawTokens.recordServiceDetokenize(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); + when(mockRawTokens.detokenize(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -1272,11 +1271,11 @@ public void testGet_successWithRedactionType() throws Exception { Map fields = new HashMap<>(); fields.put("skyflow_id", "id-redact-001"); - V1FieldRecords fieldRecords = V1FieldRecords.builder().fields(fields).build(); - V1BulkGetRecordResponse getResp = V1BulkGetRecordResponse.builder() + GetFieldRecords fieldRecords = GetFieldRecords.builder().fields(fields).build(); + BulkGetRecordResponse getResp = BulkGetRecordResponse.builder() .records(Collections.singletonList(fieldRecords)) .build(); - when(mockRecords.recordServiceBulkGetRecord(anyString(), anyString(), any(), any())).thenReturn(getResp); + when(mockRecords.getRecords(anyString(), anyString(), any(), any())).thenReturn(getResp); VaultController controller = createControllerWithMock(mockApi); @@ -1304,19 +1303,19 @@ public void testDetokenize_mixedSuccessAndError() throws Exception { when(mockApi.tokens()).thenReturn(mockTokens); when(mockTokens.withRawResponse()).thenReturn(mockRawTokens); - V1DetokenizeRecordResponse goodRecord = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse goodRecord = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("tok-good") .build(); - V1DetokenizeRecordResponse badRecord = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse badRecord = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("tok-bad") .error("token not found") .build(); - V1DetokenizeResponse detokBody = V1DetokenizeResponse.builder() + com.skyflow.generated.rest.types.DetokenizeResponse detokBody = com.skyflow.generated.rest.types.DetokenizeResponse.builder() .records(Arrays.asList(goodRecord, badRecord)) .build(); Response rawResp = buildOkHttpResponse(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); - when(mockRawTokens.recordServiceDetokenize(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); + when(mockRawTokens.detokenize(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -1343,11 +1342,11 @@ public void testTokenize_success() throws Exception { TokensClient mockTokens = Mockito.mock(TokensClient.class); when(mockApi.tokens()).thenReturn(mockTokens); - V1TokenizeRecordResponse tokenRecord = V1TokenizeRecordResponse.builder().token("tok-abc").build(); - V1TokenizeResponse tokenResp = V1TokenizeResponse.builder() + TokenizeRecordResponse tokenRecord = TokenizeRecordResponse.builder().token("tok-abc").build(); + com.skyflow.generated.rest.types.TokenizeResponse tokenResp = com.skyflow.generated.rest.types.TokenizeResponse.builder() .records(Collections.singletonList(tokenRecord)) .build(); - when(mockTokens.recordServiceTokenize(anyString(), any(), any())).thenReturn(tokenResp); + when(mockTokens.tokenize(anyString(), any(), any())).thenReturn(tokenResp); VaultController controller = createControllerWithMock(mockApi); @@ -1368,7 +1367,7 @@ public void testTokenize_apiErrorThrowsSkyflowException() throws Exception { ApiClient mockApi = Mockito.mock(ApiClient.class); TokensClient mockTokens = Mockito.mock(TokensClient.class); when(mockApi.tokens()).thenReturn(mockTokens); - when(mockTokens.recordServiceTokenize(anyString(), any(), any())) + when(mockTokens.tokenize(anyString(), any(), any())) .thenThrow(new ApiClientApiException("tokenize failed", 422, "unprocessable")); VaultController controller = createControllerWithMock(mockApi); @@ -1391,7 +1390,7 @@ public void testTokenize_apiClientExceptionThrowsSkyflowException() throws Excep ApiClient mockApi = Mockito.mock(ApiClient.class); TokensClient mockTokens = Mockito.mock(TokensClient.class); when(mockApi.tokens()).thenReturn(mockTokens); - when(mockTokens.recordServiceTokenize(anyString(), any(), any())) + when(mockTokens.tokenize(anyString(), any(), any())) .thenThrow(new ApiClientException("Network error executing HTTP request")); VaultController controller = createControllerWithMock(mockApi); @@ -1418,11 +1417,11 @@ public void testUploadFile_withFilePath() throws Exception { java.nio.file.Files.write(tmpFile.toPath(), "data".getBytes()); ApiClient mockApi = Mockito.mock(ApiClient.class); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - when(mockApi.records()).thenReturn(mockRecords); - UploadFileV2Response uploadResp = UploadFileV2Response.builder() + FilesClient mockFiles = Mockito.mock(FilesClient.class); + when(mockApi.files()).thenReturn(mockFiles); + UploadFileResponseV2 uploadResp = UploadFileResponseV2.builder() .skyflowId(java.util.Optional.of("sky-id-path")).build(); - when(mockRecords.uploadFileV2(anyString(), any(File.class), any(), any())).thenReturn(uploadResp); + when(mockFiles.uploadFileV2(anyString(), any(File.class), any(), any())).thenReturn(uploadResp); VaultController controller = createControllerWithMock(mockApi); FileUploadRequest request = FileUploadRequest.builder() @@ -1441,11 +1440,11 @@ public void testUploadFile_withBase64() throws Exception { String b64 = java.util.Base64.getEncoder().encodeToString("file content".getBytes()); ApiClient mockApi = Mockito.mock(ApiClient.class); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - when(mockApi.records()).thenReturn(mockRecords); - UploadFileV2Response uploadResp = UploadFileV2Response.builder() + FilesClient mockFiles = Mockito.mock(FilesClient.class); + when(mockApi.files()).thenReturn(mockFiles); + UploadFileResponseV2 uploadResp = UploadFileResponseV2.builder() .skyflowId(java.util.Optional.of("sky-id-b64")).build(); - when(mockRecords.uploadFileV2(anyString(), any(File.class), any(), any())).thenReturn(uploadResp); + when(mockFiles.uploadFileV2(anyString(), any(File.class), any(), any())).thenReturn(uploadResp); VaultController controller = createControllerWithMock(mockApi); FileUploadRequest request = FileUploadRequest.builder() @@ -1467,11 +1466,11 @@ public void testUploadFile_withFileObject() throws Exception { java.nio.file.Files.write(tmpFile.toPath(), "data".getBytes()); ApiClient mockApi = Mockito.mock(ApiClient.class); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - when(mockApi.records()).thenReturn(mockRecords); - UploadFileV2Response uploadResp = UploadFileV2Response.builder() + FilesClient mockFiles = Mockito.mock(FilesClient.class); + when(mockApi.files()).thenReturn(mockFiles); + UploadFileResponseV2 uploadResp = UploadFileResponseV2.builder() .skyflowId(java.util.Optional.of("sky-id-obj")).build(); - when(mockRecords.uploadFileV2(anyString(), any(File.class), any(), any())).thenReturn(uploadResp); + when(mockFiles.uploadFileV2(anyString(), any(File.class), any(), any())).thenReturn(uploadResp); VaultController controller = createControllerWithMock(mockApi); FileUploadRequest request = FileUploadRequest.builder() @@ -1492,9 +1491,9 @@ public void testUploadFile_apiError() throws Exception { java.nio.file.Files.write(tmpFile.toPath(), "data".getBytes()); ApiClient mockApi = Mockito.mock(ApiClient.class); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.uploadFileV2(anyString(), any(File.class), any(), any())) + FilesClient mockFiles = Mockito.mock(FilesClient.class); + when(mockApi.files()).thenReturn(mockFiles); + when(mockFiles.uploadFileV2(anyString(), any(File.class), any(), any())) .thenThrow(new ApiClientApiException("upload failed", 403, "forbidden")); VaultController controller = createControllerWithMock(mockApi); @@ -1519,9 +1518,9 @@ public void testUploadFile_apiClientExceptionThrowsSkyflowException() throws Exc java.nio.file.Files.write(tmpFile.toPath(), "data".getBytes()); ApiClient mockApi = Mockito.mock(ApiClient.class); - RecordsClient mockRecords = Mockito.mock(RecordsClient.class); - when(mockApi.records()).thenReturn(mockRecords); - when(mockRecords.uploadFileV2(anyString(), any(File.class), any(), any())) + FilesClient mockFiles = Mockito.mock(FilesClient.class); + when(mockApi.files()).thenReturn(mockFiles); + when(mockFiles.uploadFileV2(anyString(), any(File.class), any(), any())) .thenThrow(new ApiClientException("Network error executing HTTP request")); VaultController controller = createControllerWithMock(mockApi); @@ -1608,11 +1607,11 @@ public void testDetokenize_missingRequestIdHeaderDoesNotThrowAndRequestIdIsNull( when(mockApi.tokens()).thenReturn(mockTokens); when(mockTokens.withRawResponse()).thenReturn(mockRawTokens); - V1DetokenizeRecordResponse errRecord = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse errRecord = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("tok-bad") .error("token not found") .build(); - V1DetokenizeResponse detokBody = V1DetokenizeResponse.builder() + com.skyflow.generated.rest.types.DetokenizeResponse detokBody = com.skyflow.generated.rest.types.DetokenizeResponse.builder() .records(Collections.singletonList(errRecord)) .build(); // Deliberately no REQUEST_ID_HEADER_KEY header set (unlike buildOkHttpResponse()) @@ -1622,8 +1621,8 @@ public void testDetokenize_missingRequestIdHeaderDoesNotThrowAndRequestIdIsNull( .code(200) .message("OK") .build(); - ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); - when(mockRawTokens.recordServiceDetokenize(anyString(), any(), any())).thenReturn(httpResp); + ApiClientHttpResponse httpResp = new ApiClientHttpResponse<>(detokBody, rawResp); + when(mockRawTokens.detokenize(anyString(), any(), any())).thenReturn(httpResp); VaultController controller = createControllerWithMock(mockApi); @@ -1688,8 +1687,8 @@ public void testGet_recordsOptionalAbsentReturnsEmptyData() throws Exception { RecordsClient mockRecords = Mockito.mock(RecordsClient.class); when(mockApi.records()).thenReturn(mockRecords); - V1BulkGetRecordResponse getResp = V1BulkGetRecordResponse.builder().build(); - when(mockRecords.recordServiceBulkGetRecord(anyString(), anyString(), any(), any())).thenReturn(getResp); + BulkGetRecordResponse getResp = BulkGetRecordResponse.builder().build(); + when(mockRecords.getRecords(anyString(), anyString(), any(), any())).thenReturn(getResp); VaultController controller = createControllerWithMock(mockApi); diff --git a/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java b/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java deleted file mode 100644 index 99442682..00000000 --- a/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.skyflow.vault.detect; - -import com.skyflow.enums.DetectEntities; -import com.skyflow.enums.DetectOutputTranscriptions; -import com.skyflow.enums.MaskingMethod; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; -import com.skyflow.errors.SkyflowException; -import com.skyflow.utils.validations.Validations; -import org.junit.Assert; -import org.junit.Test; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; - -public class DeidentifyFileRequestTest { - - @Test - public void testBuilderAndGetters() { - File file = new File("test.txt"); - FileInput fileInput = FileInput.builder().file(file).build(); - DetectEntities entity = DetectEntities.DOB; - MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; - DetectOutputTranscriptions transcription = DetectOutputTranscriptions.TRANSCRIPTION; - String outputDir = "/tmp/output"; - int waitTime = 42; - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(Arrays.asList(entity)) - .allowRegexList(Arrays.asList("a.*")) - .restrictRegexList(Arrays.asList("b.*")) - .maskingMethod(maskingMethod) - .outputProcessedImage(true) - .outputOcrText(true) - .outputProcessedAudio(true) - .outputTranscription(transcription) - .outputDirectory(outputDir) - .waitTime(waitTime) - .build(); - - Assert.assertEquals(entity, request.getEntities().get(0)); - Assert.assertEquals("a.*", request.getAllowRegexList().get(0)); - Assert.assertEquals("b.*", request.getRestrictRegexList().get(0)); - Assert.assertEquals(maskingMethod, request.getMaskingMethod()); - Assert.assertTrue(request.getOutputProcessedImage()); - Assert.assertTrue(request.getOutputOcrText()); - Assert.assertTrue(request.getOutputProcessedAudio()); - Assert.assertEquals(transcription, request.getOutputTranscription()); - Assert.assertEquals(outputDir, request.getOutputDirectory()); - Assert.assertEquals(Integer.valueOf(waitTime), request.getWaitTime()); - } - - @Test - public void testBuilderDefaults() { - DeidentifyFileRequest request = DeidentifyFileRequest.builder().build(); - Assert.assertFalse(request.getOutputProcessedImage()); - Assert.assertFalse(request.getOutputOcrText()); - Assert.assertFalse(request.getOutputProcessedAudio()); - Assert.assertNull(request.getOutputDirectory()); - Assert.assertNull(request.getWaitTime()); - } - - @Test - public void testBuilderWithFilePath() { - String filePath = "/tmp/test.txt"; - FileInput fileInput = FileInput.builder().filePath(filePath).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(Collections.singletonList(DetectEntities.DOB)) - .build(); - - Assert.assertEquals(filePath, request.getFileInput().getFilePath()); - Assert.assertNull(request.getFileInput().getFile()); - } - - @Test - public void testBuilderWithFileAndFilePath() { - File file = new File("test.txt"); - String filePath = "/tmp/test.txt"; - FileInput fileInput = FileInput.builder().file(file).filePath(filePath).build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(Collections.singletonList(DetectEntities.DOB)) - .build(); - - Assert.assertEquals(file, request.getFileInput().getFile()); - Assert.assertEquals(filePath, request.getFileInput().getFilePath()); - } - - @Test - public void testBuilderWithNullFileAndFilePath() { - FileInput fileInput = FileInput.builder().build(); - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .file(fileInput) - .entities(Collections.singletonList(DetectEntities.DOB)) - .build(); - - Assert.assertNull(request.getFileInput().getFile()); - Assert.assertNull(request.getFileInput().getFilePath()); - } - - @Test - public void testValidateDeidentifyFileRequestWithNullFileInputThrowsSkyflowException() { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .entities(Collections.singletonList(DetectEntities.DOB)) - .build(); - try { - Validations.validateDeidentifyFileRequest(request); - Assert.fail("Should have thrown an exception"); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage(), e.getMessage()); - } - } - - @Test - public void testBuilderNullBooleansFallToFalse() { - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .outputProcessedImage(null) - .outputOcrText(null) - .outputProcessedAudio(null) - .build(); - Assert.assertFalse(request.getOutputProcessedImage()); - Assert.assertFalse(request.getOutputOcrText()); - Assert.assertFalse(request.getOutputProcessedAudio()); - } - - @Test - public void testBuilderWithTokenFormatTransformationsPixelDensityMaxResolutionBleep() { - TokenFormat tf = TokenFormat.builder().build(); - Transformations tr = new Transformations(null); - AudioBleep bleep = AudioBleep.builder().frequency(800.0).build(); - - DeidentifyFileRequest request = DeidentifyFileRequest.builder() - .tokenFormat(tf) - .transformations(tr) - .pixelDensity(150) - .maxResolution(1920) - .bleep(bleep) - .build(); - - Assert.assertEquals(tf, request.getTokenFormat()); - Assert.assertEquals(tr, request.getTransformations()); - Assert.assertEquals(150, request.getPixelDensity().intValue()); - Assert.assertEquals(1920, request.getMaxResolution().intValue()); - Assert.assertEquals(bleep, request.getBleep()); - } -} \ No newline at end of file diff --git a/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java b/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java deleted file mode 100644 index d3946719..00000000 --- a/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.skyflow.vault.detect; - -import com.skyflow.generated.rest.types.DeidentifiedFileOutputProcessedFileExtension; -import com.skyflow.generated.rest.types.DeidentifiedFileOutputProcessedFileType; -import org.junit.Assert; -import org.junit.Test; - -import java.io.File; -import java.util.Collections; - -public class DeidentifyFileResponseTest { - - @Test - public void testAllGettersAndToString() { - File fileObject = new File("test-path.txt"); - String file = "test-path.txt"; - String type = "pdf"; - String extension = ".pdf"; - Integer wordCount = 100; - Integer charCount = 500; - Float sizeInKb = 123.45F; - Float durationInSeconds = 12.3F; - Integer pageCount = 5; - Integer slideCount = 0; - FileEntityInfo entityInfo = new FileEntityInfo("PERSON", DeidentifiedFileOutputProcessedFileType.ENTITIES, DeidentifiedFileOutputProcessedFileExtension.PDF); - java.util.List entities = Collections.singletonList(entityInfo); - String runId = "run-123"; - String status = "SUCCESS"; - FileInfo fileInfo = new FileInfo(fileObject); - - DeidentifyFileResponse response = new DeidentifyFileResponse( - fileInfo, file, type, extension, wordCount, charCount, sizeInKb, - durationInSeconds, pageCount, slideCount, entities, runId, status - ); - - Assert.assertEquals(type, response.getType()); - Assert.assertEquals(extension, response.getExtension()); - Assert.assertEquals(wordCount, response.getWordCount()); - Assert.assertEquals(charCount, response.getCharCount()); - Assert.assertEquals(sizeInKb, response.getSizeInKb()); - Assert.assertEquals(durationInSeconds, response.getDurationInSeconds()); - Assert.assertEquals(pageCount, response.getPageCount()); - Assert.assertEquals(slideCount, response.getSlideCount()); - Assert.assertEquals(entities, response.getEntities()); - Assert.assertEquals(runId, response.getRunId()); - Assert.assertEquals(status, response.getStatus()); - - // toString should return a JSON string containing all fields - String json = response.toString(); - Assert.assertTrue(json.contains(file)); - Assert.assertTrue(json.contains(type)); - Assert.assertTrue(json.contains(extension)); - Assert.assertTrue(json.contains(runId)); - Assert.assertTrue(json.contains(status)); - Assert.assertTrue(json.contains("PERSON")); - Assert.assertEquals(fileInfo, response.getFile()); - Assert.assertEquals(file, response.getFileBase64()); - } - - @Test - public void testShortConstructorAndGetters() { - DeidentifyFileResponse response = new DeidentifyFileResponse("run-456", "PENDING"); - Assert.assertEquals("run-456", response.getRunId()); - Assert.assertEquals("PENDING", response.getStatus()); - Assert.assertNull(response.getFile()); - Assert.assertNull(response.getFileBase64()); - Assert.assertNull(response.getWordCount()); - } -} \ No newline at end of file diff --git a/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java b/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java deleted file mode 100644 index 193a898e..00000000 --- a/skyvault/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java +++ /dev/null @@ -1,299 +0,0 @@ -package com.skyflow.vault.detect; - -import com.skyflow.enums.DetectEntities; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; -import com.skyflow.errors.SkyflowException; -import com.skyflow.utils.validations.Validations; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static com.skyflow.errors.ErrorMessage.InvalidTextInDeIdentify; - -public class DeidentifyTextTests { - - private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; - - private static final String text = "Sensitive data to deidentify"; - private static final List detectEntities = new ArrayList<>(); - private static final List allowRegexList = new ArrayList<>(); - private static final List restrictRegexList = new ArrayList<>(); - private static final TokenFormat tokenFormat = TokenFormat.builder() - .vaultToken(detectEntities) - .entityUniqueCounter(detectEntities) - .entityOnly(detectEntities) - .build(); - - private static Transformations transformations = null; - - - @BeforeClass - public static void setup() { - detectEntities.add(DetectEntities.NAME); - detectEntities.add(DetectEntities.DOB); - - allowRegexList.add("^[A-Za-z]+$"); - restrictRegexList.add("([0-9]{3}-[0-9]{2}-[0-9]{4})"); - - transformations = new Transformations( - new DateTransformation(20, 5, detectEntities) - ); - } - - - @Test - public void testValidInputInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder() - .text(text) - .entities(detectEntities) - .allowRegexList(allowRegexList) - .restrictRegexList(restrictRegexList) - .tokenFormat(tokenFormat) - .transformations(transformations) - .build(); - - Validations.validateDeidentifyTextRequest(request); - Assert.assertEquals(detectEntities, request.getEntities()); - Assert.assertEquals(allowRegexList, request.getAllowRegexList()); - Assert.assertEquals(restrictRegexList, request.getRestrictRegexList()); - Assert.assertEquals(tokenFormat, request.getTokenFormat()); - Assert.assertEquals(transformations, request.getTransformations()); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - - @Test - public void testNullRequestInDeidentifyTextRequestValidations() { - try { - Validations.validateDeidentifyTextRequest(null); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.DeidentifyTextRequestNull.getMessage(), e.getMessage()); - } - } - - @Test - public void testNullTextInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text(null).build(); - Validations.validateDeidentifyTextRequest(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(InvalidTextInDeIdentify.getMessage(), e.getMessage()); - } - } - - @Test - public void testEmptyTextInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); - Validations.validateDeidentifyTextRequest(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(InvalidTextInDeIdentify.getMessage(), e.getMessage()); - } - } - - @Test - public void testEmptyEntitiesInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder() - .text(text) - .entities(new ArrayList<>()) - .build(); - Validations.validateDeidentifyTextRequest(request); - Assert.assertTrue(request.getEntities().isEmpty()); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - - @Test - public void testNoEntitiesInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); - Validations.validateDeidentifyTextRequest(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - - @Test - public void testEmptyAllowRegexListInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder() - .text(text) - .allowRegexList(new ArrayList<>()) - .build(); - Validations.validateDeidentifyTextRequest(request); - Assert.assertTrue(request.getAllowRegexList().isEmpty()); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - @Test - public void testEmptyRestrictRegexListInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder() - .text(text) - .restrictRegexList(new ArrayList<>()) - .build(); - Validations.validateDeidentifyTextRequest(request); - Assert.assertTrue(request.getRestrictRegexList().isEmpty()); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - - @Test - public void testNullTokenFormatInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder() - .text(text) - .entities(detectEntities) - .allowRegexList(allowRegexList) - .restrictRegexList(restrictRegexList) - .tokenFormat(null) - .build(); - Validations.validateDeidentifyTextRequest(request); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - @Test - public void testNoTransformationsInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder() - .text(text) - .entities(detectEntities) - .allowRegexList(allowRegexList) - .restrictRegexList(restrictRegexList) - .tokenFormat(tokenFormat) - .build(); - Validations.validateDeidentifyTextRequest(request); - Assert.assertNull(request.getTransformations()); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testNullOrEmptyTransformationsInDeidentifyTextRequestValidations() { - try { - DeidentifyTextRequest request = DeidentifyTextRequest.builder() - .text(text) - .entities(detectEntities) - .allowRegexList(allowRegexList) - .restrictRegexList(restrictRegexList) - .tokenFormat(tokenFormat) - .transformations(null) - .build(); - Validations.validateDeidentifyTextRequest(request); - Assert.assertNull(request.getTransformations()); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - @Test - public void testDeidentifyResponse() { - try { - List entityInfos = new ArrayList<>(); - int wordCount = 5; - int charCount = 30; - DeidentifyTextResponse response = new DeidentifyTextResponse(text, entityInfos, wordCount, charCount); - Assert.assertEquals(text, response.getProcessedText()); - Assert.assertEquals(wordCount, response.getWordCount()); - Assert.assertEquals(charCount, response.getCharCount()); - } catch (Exception e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testDeidentifyResponseGetEntitiesAndToString() { - TextIndex ti = new TextIndex(0, 4); - TextIndex pi = new TextIndex(5, 9); - java.util.Map scores = new java.util.HashMap<>(); - scores.put("confidence", 0.95); - EntityInfo ei = new EntityInfo("tok1", "John", ti, pi, "NAME", scores); - - List entities = new ArrayList<>(); - entities.add(ei); - - DeidentifyTextResponse response = new DeidentifyTextResponse(text, entities, 1, 10); - Assert.assertEquals(entities, response.getEntities()); - String json = response.toString(); - Assert.assertNotNull(json); - Assert.assertTrue(json.contains(text)); - } - - @Test - public void testTextIndex() { - TextIndex ti = new TextIndex(3, 7); - Assert.assertEquals(3, ti.getStart()); - Assert.assertEquals(7, ti.getEnd()); - String json = ti.toString(); - Assert.assertNotNull(json); - Assert.assertTrue(json.contains("3")); - } - - @Test - public void testEntityInfoGetters() { - TextIndex ti = new TextIndex(0, 4); - TextIndex pi = new TextIndex(5, 9); - java.util.Map scores = new java.util.HashMap<>(); - scores.put("confidence", 0.9); - EntityInfo ei = new EntityInfo("tok1", "Alice", ti, pi, "NAME", scores); - Assert.assertEquals("tok1", ei.getToken()); - Assert.assertEquals("Alice", ei.getValue()); - Assert.assertEquals(ti, ei.getTextIndex()); - Assert.assertEquals(pi, ei.getProcessedIndex()); - Assert.assertEquals("NAME", ei.getEntity()); - Assert.assertEquals(scores, ei.getScores()); - } - - @Test - public void testTokenFormatGetters() { - TokenFormat tf = TokenFormat.builder() - .vaultToken(detectEntities) - .entityUniqueCounter(detectEntities) - .entityOnly(detectEntities) - .build(); - Assert.assertEquals(detectEntities, tf.getVaultToken()); - Assert.assertEquals(detectEntities, tf.getEntityUniqueCounter()); - Assert.assertEquals(detectEntities, tf.getEntityOnly()); - Assert.assertNotNull(tf.getDefault()); - } - - @Test - public void testTokenFormatDefaultTypeNull() { - TokenFormat tf = TokenFormat.builder().defaultType(null).build(); - Assert.assertEquals(com.skyflow.enums.TokenType.ENTITY_UNIQUE_COUNTER, tf.getDefault()); - } - - @Test - public void testTokenFormatDefaultTypeNonNull() { - TokenFormat tf = TokenFormat.builder() - .defaultType(com.skyflow.enums.TokenType.VAULT_TOKEN) - .build(); - Assert.assertEquals(com.skyflow.enums.TokenType.VAULT_TOKEN, tf.getDefault()); - } -} diff --git a/skyvault/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java b/skyvault/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java deleted file mode 100644 index d77ddb6f..00000000 --- a/skyvault/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.skyflow.vault.detect; - -import com.skyflow.generated.rest.types.DeidentifiedFileOutputProcessedFileExtension; -import com.skyflow.generated.rest.types.DeidentifiedFileOutputProcessedFileType; -import org.junit.Assert; -import org.junit.Test; - -public class FileEntityInfoTest { - - @Test - public void testConstructorAndGetters() { - String file = "entity.pdf"; - DeidentifiedFileOutputProcessedFileType type = DeidentifiedFileOutputProcessedFileType.ENTITIES; - String extension = "pdf"; - - FileEntityInfo info = new FileEntityInfo(file, type, DeidentifiedFileOutputProcessedFileExtension.PDF); - - Assert.assertEquals(file, info.getFile()); - Assert.assertEquals(type.toString(), info.getType()); - Assert.assertEquals(extension, info.getExtension()); - } -} \ No newline at end of file diff --git a/skyvault/src/test/java/com/skyflow/vault/detect/FileInfoTest.java b/skyvault/src/test/java/com/skyflow/vault/detect/FileInfoTest.java deleted file mode 100644 index 29a81f6a..00000000 --- a/skyvault/src/test/java/com/skyflow/vault/detect/FileInfoTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.skyflow.vault.detect; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -public class FileInfoTest { - - @Test - public void testFileInfoFields() throws IOException { - // Create a temp file - File tempFile = File.createTempFile("testfileinfo", ".txt"); - tempFile.deleteOnExit(); - - // Write some content to ensure size > 0 - FileWriter writer = new FileWriter(tempFile); - writer.write("Hello Skyflow!"); - writer.close(); - - FileInfo fileInfo = new FileInfo(tempFile); - - Assert.assertEquals(tempFile.getName(), fileInfo.getName()); - Assert.assertEquals(tempFile.length(), fileInfo.getSize()); - Assert.assertEquals("", fileInfo.getType()); - Assert.assertEquals(tempFile.lastModified(), fileInfo.getLastModified()); - } - - @Test - public void testFileInfoWithNonExistentFile() { - File fakeFile = new File("nonexistentfile.txt"); - FileInfo fileInfo = new FileInfo(fakeFile); - - Assert.assertEquals("nonexistentfile.txt", fileInfo.getName()); - Assert.assertEquals(0, fileInfo.getSize()); - Assert.assertEquals("", fileInfo.getType()); - Assert.assertEquals(0, fileInfo.getLastModified()); - } -} \ No newline at end of file diff --git a/skyvault/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java b/skyvault/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java deleted file mode 100644 index 8ed9716a..00000000 --- a/skyvault/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java +++ /dev/null @@ -1,169 +0,0 @@ -package com.skyflow.vault.detect; - -import com.skyflow.enums.DetectEntities; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.ErrorMessage; -import com.skyflow.errors.SkyflowException; -import com.skyflow.utils.validations.Validations; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static com.skyflow.errors.ErrorMessage.InvalidTextInReIdentify; - -public class ReidentifyTextTests { - - private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; - - private static final String text = "Sensitive data to reidentify"; - private static final List redactedEntities = new ArrayList<>(); - private static final List maskedEntities = new ArrayList<>(); - private static final List plainTextEntities = new ArrayList<>(); - - @BeforeClass - public static void setup() { - redactedEntities.add(DetectEntities.NAME); - redactedEntities.add(DetectEntities.DOB); - - maskedEntities.add(DetectEntities.USERNAME); - - plainTextEntities.add(DetectEntities.PHONE_NUMBER); - } - - @Test - public void testValidInputInReidentifyTextRequestValidations() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder() - .text(text) - .redactedEntities(redactedEntities) - .maskedEntities(maskedEntities) - .plainTextEntities(plainTextEntities) - .build(); - - Validations.validateReidentifyTextRequest(request); - Assert.assertEquals(text, request.getText()); - Assert.assertEquals(redactedEntities, request.getRedactedEntities()); - Assert.assertEquals(maskedEntities, request.getMaskedEntities()); - Assert.assertEquals(plainTextEntities, request.getPlainTextEntities()); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testNullRequestInReidentifyTextRequestValidations() { - try { - Validations.validateReidentifyTextRequest(null); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.ReidentifyTextRequestNull.getMessage(), e.getMessage()); - } - } - - @Test - public void testNoTextInReidentifyTextRequestValidations() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder().build(); - Validations.validateReidentifyTextRequest(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - @Test - public void testNullTextInReidentifyTextRequestValidations() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder() - .text(null) - .build(); - Validations.validateReidentifyTextRequest(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(InvalidTextInReIdentify.getMessage(), e.getMessage()); - } - } - - @Test - public void testEmptyTextInReidentifyTextRequestValidations() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder() - .text("") - .build(); - Validations.validateReidentifyTextRequest(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(InvalidTextInReIdentify.getMessage(), e.getMessage()); - } - } - - - @Test - public void testEmptyRedactedEntitiesInReidentifyTextRequestValidations() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder() - .text(text) - .redactedEntities(new ArrayList<>()) - .build(); - Validations.validateReidentifyTextRequest(request); - Assert.assertTrue(request.getRedactedEntities().isEmpty()); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - - @Test - public void testEmptyMaskedEntitiesInReidentifyTextRequestValidations() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder() - .text(text) - .maskedEntities(new ArrayList<>()) - .build(); - Validations.validateReidentifyTextRequest(request); - Assert.assertTrue(request.getMaskedEntities().isEmpty()); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - @Test - public void testEmptyPlainTextEntitiesInReidentifyTextRequestValidations() { - try { - ReidentifyTextRequest request = ReidentifyTextRequest.builder() - .text(text) - .plainTextEntities(new ArrayList<>()) - .build(); - Validations.validateReidentifyTextRequest(request); - Assert.assertTrue(request.getPlainTextEntities().isEmpty()); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - } - } - - - @Test - public void testReidentifyResponse() { - try { - ReidentifyTextResponse response = new ReidentifyTextResponse(text); - Assert.assertEquals(text, response.getProcessedText()); - } catch (Exception e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testReidentifyResponseToString() { - ReidentifyTextResponse response = new ReidentifyTextResponse(text); - String json = response.toString(); - Assert.assertNotNull(json); - Assert.assertTrue(json.contains(text)); - } -} \ No newline at end of file diff --git a/skyvault/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/skyvault/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index 3d76215a..07e1107e 100644 --- a/skyvault/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/skyvault/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -5,7 +5,6 @@ import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.types.DetokenizeRecordResponseValueType; -import com.skyflow.generated.rest.types.V1DetokenizeRecordResponse; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; @@ -201,7 +200,7 @@ public void testDetokenizeDataNullRedactionTypeDefaultsToDefault() { @Test public void testDetokenizeRecordResponseNullValue() { - V1DetokenizeRecordResponse record = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse record = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("tok-null-val") .build(); DetokenizeRecordResponse response = new DetokenizeRecordResponse(record); @@ -210,12 +209,28 @@ public void testDetokenizeRecordResponseNullValue() { Assert.assertNull(response.getRequestId()); } + @Test + public void testLegacyGeneratedRecordConstructorStillWorks() { + com.skyflow.generated.rest.types.V1DetokenizeRecordResponse legacy = + com.skyflow.generated.rest.types.V1DetokenizeRecordResponse.builder() + .token("tok-legacy") + .value("legacy-value") + .valueType(DetokenizeRecordResponseValueType.STRING) + .build(); + DetokenizeRecordResponse response = new DetokenizeRecordResponse(legacy, "req-legacy"); + Assert.assertEquals("tok-legacy", response.getToken()); + Assert.assertEquals("legacy-value", response.getValue()); + Assert.assertEquals("STRING", response.getType()); + Assert.assertEquals("req-legacy", response.getRequestId()); + Assert.assertNull(new DetokenizeRecordResponse(legacy).getRequestId()); + } + @Test public void testDetokenizeRecordResponseNoneValueTypeBecomesNull() { - V1DetokenizeRecordResponse record = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse record = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("tok-none-type") .value("some-value") - .valueType(DetokenizeRecordResponseValueType.NONE) + .valueType(DetokenizeRecordResponseValueType.valueOf("NONE")) .build(); DetokenizeRecordResponse response = new DetokenizeRecordResponse(record); Assert.assertNull("NONE valueType should be normalised to null", response.getType()); @@ -255,14 +270,14 @@ public void testDetokenizeRequestBuilderDownloadUrlNull() { @Test public void testDetokenizeResponse() { try { - V1DetokenizeRecordResponse record1 = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse record1 = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("1234-5678-9012-3456") .value("4111111111111111") .valueType(DetokenizeRecordResponseValueType.STRING) .build(); DetokenizeRecordResponse field = new DetokenizeRecordResponse(record1); - V1DetokenizeRecordResponse record2 = V1DetokenizeRecordResponse.builder() + com.skyflow.generated.rest.types.DetokenizeRecordResponse record2 = com.skyflow.generated.rest.types.DetokenizeRecordResponse.builder() .token("3456-7890-1234-5678") .value("") .error("Invalid token")