Skip to content

Commit e7b5167

Browse files
SK-2814: java public interface cleanup (#314)
* docs: add Java SDK nomenclature cleanup design spec Captures the design for public interface renames per the server-side SDK nomenclature changes spec: credential field fallbacks (clientId/keyId/tokenUri), skyflow_id→skyflowId in Get/Query responses, and QueryResponse errors/tokenizedData field additions. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: clarify tokenizedData reasoning in nomenclature cleanup spec Adds explanation for why tokenizedData change is valid despite the Query API currently not returning tokens — based on V1FieldRecords schema support and cross-SDK consistency requirement. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: expand reasoning in Java nomenclature cleanup spec Adds detailed rationale to each design section: why the naming convention matters, why the fallback strategy was chosen over a hard cut, why skyflow_id normalization is inconsistent today, the tokenizedData API schema vs docs discrepancy, and why getErrors() is missing only from QueryResponse. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: correct tokenizedData implementation rationale in spec Clarifies that ignoring record.getTokens() in getFormattedQueryRecord is intentional (Query API cannot return tokens), and that the fix is to promote the toString() hack into a real always-empty field rather than reading from the API response. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: remove tokenizedData from scope in nomenclature cleanup spec Query API cannot return tokens; the toString() inconsistency is not worth fixing since callers have no reason to access tokenizedData programmatically on query results. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: add implementation plan for Java SDK nomenclature cleanup 5-task TDD plan covering credential field renames with fallback, skyflow_id normalisation in Get/Query responses, and QueryResponse getErrors() accessor. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * feat: accept clientId/keyId/tokenUri in BearerToken with fallback to old form Add fallback lookup logic so getBearerTokenFromCredentials tries new camelCase keys (clientId, keyId, tokenUri) first and falls back to the legacy all-caps forms (clientID, keyID, tokenURI) for backward compatibility during migration. Add testBearerTokenWithNewFormCredentialKeys to verify the new key form is recognized end-to-end. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * feat: accept clientId/keyId in SignedDataTokens with fallback to old form Add fallback logic to GenerateSignedTokensFromCredentials so both new-form keys (clientId/keyId) and legacy all-caps keys (clientID/keyID) are accepted during migration. Mirrors the pattern already applied to BearerToken.java. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * feat: normalise skyflow_id to skyflowId in Get and Query response maps Insert and Update responses already used camelCase skyflowId; Get and Query were passing through the raw wire-format snake_case key. Add the rename in getFormattedGetRecord and getFormattedQueryRecord, and add reflection-based unit tests to cover both formatters. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * feat: add getErrors() accessor to QueryResponse Adds a private final errors field (always null) and its public accessor to QueryResponse, matching the pattern in GetResponse and InsertResponse. Removes the hardcoded responseObject.add("errors", null) from toString() since serializeNulls on the declared field handles it automatically. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: audit confirms no setFooID/getFooID violations in public API * chore: add Claude Code setup (CLAUDE.md + .claude/) Adapted from skyflow-node PR #305. Includes: - CLAUDE.md with project overview, structure, naming conventions, build commands - .claude/settings.json with PostToolUse compile+checkstyle hooks, PreToolUse generated-code guard, Stop notification; paths are relative (no hardcoded user dirs) - .claude/commands/: code-review, code-security, sdk-sample, test slash commands Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: fix gaps and inaccuracies in Claude setup files - CLAUDE.md: add vault/bin/ package, all 5 controllers, pre-existing test failure baseline - settings.json: fix checkstyle hook to print violations (was silently swallowing output with capture_output=True) - sdk-sample.md: fix InsertOptions (doesn't exist), correct sample package structure, correct credential type per feature - code-review.md: fix validation location (controller not build()), fix HashMap rule (SDK pattern is raw HashMaps) - test.md: document pre-existing failures, note checkstyle failsOnError Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: add v2 backward compat + deprecation warnings implementation plan 6-task TDD plan: restore skyflow_id key alongside skyflowId in Get/Query responses, add WARN deprecation logs for old credential fields, Javadoc on affected response methods. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: update deprecation messages to say 'upcoming release' not 'v3' Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: add [DEPRECATED] prefix to deprecation log messages per industry standard Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: add PM-facing document for v2 public interface changes and deprecation Non-technical overview of credential field renames and skyflow_id response key deprecation — covers customer impact, deprecation warnings, migration guide, and what is NOT changing. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: add downloadURL→downloadUrl deprecation to plan and PM doc - Deprecation plan: add Task 6 for GetRequest + DetokenizeRequest with @deprecated annotation approach (compile-time signal vs runtime log) - PM doc: add section 3 for downloadURL rename with migration example Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: remove SDK-level field value null/empty validation from Insert and Update The Skyflow API accepts additionalProperties of Any type including null and empty strings. SDK should not add validation on top of BE — pass through and let BE decide. Removed: - value == null/isEmpty check in validateInsertRequest - value == null/isEmpty check in validateUpdateRequest - value == null/isEmpty check in validateTokensMapWithTokenStrict - values.isEmpty() check in validateInsertRequest (no minItems in API spec) Kept: - values == null check (NPE guard — cannot iterate null array) - key == null/isEmpty check (null keys cannot be JSON-serialized) Deleted 6 tests that asserted on the removed behaviour. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: add IDE autocomplete behavior for deprecation signals - PM doc: new section explaining how @deprecated(forRemoval) shows in IntelliJ/VS Code autocomplete (strikethrough, orange underline, tooltip with clickable link to new method) vs runtime WARN log for map keys - Deprecation plan: update downloadURL tasks to use @deprecated(since="2.1", forRemoval=true) + {link} for stronger IDE signal Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: segregate code smells into dedicated section in code-review command Splits old Section 6 into: - Section 6: Code quality (actionable correctness checks) - Section 7: Code smells (structural signals, flagged at Smell severity) Code smell catalogue covers: long methods/classes, business logic in data classes, toString() with logic, deep nesting, magic numbers, raw HashMap chains, dead code, stale comments, temporary fields. Severity table clarified: Critical/Bug/Edge Case/Quality = fix before merge; Smell = flag and track. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: add DEPRECATED_SKYFLOW_ID_KEY log entry to InfoLogs * fix: restore skyflow_id key in Get/Query responses for v2 backward compat Both skyflow_id (deprecated) and skyflowId (new form) are now present in response maps simultaneously. WARN log emitted per record. * docs: add deprecation Javadoc for skyflow_id key in GetResponse and QueryResponse * feat: deprecate downloadURL in favour of downloadUrl in GetRequest and DetokenizeRequest Old downloadURL() methods kept as @deprecated(forRemoval=true) delegates. Runtime WARN log emitted on old form usage. 100% test coverage: new form, deprecated form, default value for both classes. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: update CLAUDE.md — add code-smell command, update slash commands Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: update deprecation plan and PM doc - credentials permanently supported Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * test: add new-form downloadUrl tests alongside deprecated downloadURL tests Both old (downloadURL) and new (downloadUrl) builder methods tested: - GetTests: 2 new tests for downloadUrl() with cross-assertion on deprecated getDownloadURL() returning same value - DetokenizeTests: 1 new test same pattern - VaultClientTests: 1 new integration test for DetokenizeRequest.downloadUrl() Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: changes to claude * docs: migrate V1-to-V2 guide from README to docs/, update CHANGELOG - Extract 260-line migration section from README.md to docs/migrate_to_v2.md following the pattern established in skyflow-node PR #258 - README now links to docs/migrate_to_v2.md instead of inline content - docs/migrate_to_v2.md adds v2.1+ sections for credential field renames and skyflow_id deprecation (new content) - CHANGELOG.md: add v2.0.4 release notes covering nomenclature changes, backward compat deprecations, and validation removal Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: simplify CHANGELOG — remove v1 entries, keep only v2.0.4 Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: simplify CHANGELOG to point to GitHub and Maven releases Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: add v2 banner to README with migration link and EOL notice Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: use release notes link instead of CHANGELOG in banner Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * docs: update README banner to v2.1.x announcement Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * revert: remove .claude/ and CLAUDE.md — will be raised as separate PR from main Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: remove superpowers planning docs from repo Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: ignore docs/superpowers/ — keep planning docs local only Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: update cspell config — British English words, Maven flags, ignore paths Added words: serialise/d/s, normalise/d/s/Normalises, behaviour/s/Behaviour, sanitisation, recognised, unrecognised, prioritised Added regex: /-D[A-Za-z][A-Za-z0-9.]*/g to ignore Maven -D flags Added ignorePaths: RUNNING_SAMPLES.md, docs/superpowers/** Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: remove v2-public-interface-changes.md Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: replace real RSA key with fake key in BearerTokenTests Real 2048-bit RSA key replaced with fake base64 value. Assertion updated from InvalidTokenUri to InvalidKeySpec — still proves all credential fields were resolved (failure is at RSA parsing, not field lookup). Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: guard against null in DetokenizeRequest.downloadUrl(null) Calling .downloadUrl(null) previously stored null in the field, creating an NPE risk for callers who read getDownloadUrl() back without a null check. Now null -> false (matching the default), consistent with the continueOnError(null) guard in the same builder. Added test: testDetokenizeRequestDownloadUrlNullTreatedAsFalse Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * chore: remove dead error constants after validation removal EmptyValues, EmptyValueInValues, EmptyValueInTokens (ErrorMessage) and EMPTY_VALUES, EMPTY_OR_NULL_VALUE_IN_VALUES, EMPTY_OR_NULL_VALUE_IN_TOKENS (ErrorLogs) are unreachable since the SDK-level null/empty field validation was removed. Deleted to prevent accidental re-wiring. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * Revert "fix: guard against null in DetokenizeRequest.downloadUrl(null)" This reverts commit a802668. * test: add positive tests for permissive Insert validation behaviour Three new tests assert that previously-blocked inputs now pass SDK validation (SDK defers to BE per API spec additionalProperties: Any type): - Empty values array [] passes - Null field value passes - Empty string field value passes Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix banner * feat: port PR #273 changes — raw body support, URL encoding, null-safe request ID - Add EMPTY_STRING, QUOTE, HTTPS_PROTOCOL, CURLY_PLACEHOLDER and HttpUtilityExtra (RAW_BODY_KEY, SDK_GENERATED_PREFIX) to Constants - HttpUtility: conditional content-type header, __raw_body__ passthrough, UUID fallback when server omits x-request-id, URL-encoded form params - Utils: URL-encode path and query params with graceful fallback - Validations: accept String request bodies for non-JSON content types - ConnectionController: wrap String bodies in __raw_body__ for non-JSON content types; fall back to raw string when response is not JSON - InfoLogs: "Bearer token is expired" → "Bearer token is invalid or expired" - HttpUtilityTests: add raw body, no content-type, null request ID and special-character form-encoding tests Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: guard unsafe Optional.get() calls and remove dead statement in DetectController - Remove dead statement `response.getEntities().get(0).getFile()` that discarded its result and threw IndexOutOfBoundsException/NPE when entities was null or empty (C1); the guarded block below already handles entity processing correctly - Replace unguarded `response.getOutput().get()` in getFirstOutput() with `.orElse(null)` so an absent output Optional returns null instead of throwing NoSuchElementException (C2) - Replace unguarded `firstOutput.getProcessedFileExtension().get().toString()` with `.map(Object::toString).orElse(UNKNOWN)`, reusing the already-computed Optional and matching the safe pattern used for processedFileType one line above (C3) - Add 4 unit tests covering all three fixes via reflection Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: guard Optional.get() in delete, close FileReader, guard empty form-encode - VaultController.delete: replace unguarded getRecordIdResponse().get() with .orElse(Collections.emptyList()) so an absent field in the API response returns an empty list instead of throwing NoSuchElementException (M2) - BearerToken, SignedDataTokens: wrap FileReader in try/finally to guarantee close() is called even when JsonParser throws JsonSyntaxException; close IOException is intentionally swallowed since the parse already completed (M3) - HttpUtility.formatJsonToFormEncodedString: guard against empty entry set so substring(0, -1) is not called on an empty StringBuilder (M4) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs: update README for v2.1 public interface changes - Replace deprecated credential key names in examples: clientID→clientId, keyID→keyId, TokenURI→tokenUri - Update Insert, Get, and Query response examples to use skyflowId (the SDK has always returned skyflowId for Insert; Get/Query now return skyflowId as the primary key) - Add deprecation note after each affected response block: skyflow_id is deprecated and will be removed in an upcoming release Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: do not generate SDK-side requestId when server omits x-request-id header When the response carries no x-request-id header, set requestID to null instead of fabricating a UUID with an SDK-Generated- prefix. A null value is the honest signal to callers that no server request ID is available. Also removes the now-unused UUID import. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat: add printWarningLogOnce to suppress per-record deprecation spam Replace per-record printWarningLog calls for DEPRECATED_SKYFLOW_ID_KEY with printWarningLogOnce so the deprecation notice fires at most once per JVM session regardless of result set size. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test: fix testSendRequestWithNullRequestId to assert null requestId The SDK no longer generates a fallback UUID when the server omits x-request-id; getRequestID() now returns null. Update the assertion to match the new behaviour. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs: fix request_index to requestIndex in README response examples The SDK puts camelCase requestIndex in response maps; the README examples incorrectly showed snake_case request_index. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: readme * docs: add v2.1.0 upgrade banner and migration guide to v1 README (#310) Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> * feat: accept camelCase skyflowId in UpdateRequest and fire deprecation warnings per-request - UpdateRequest.data now accepts 'skyflowId' (preferred) alongside deprecated 'skyflow_id' - extractUpdateSkyflowId() prefers camelCase key, emits WARN-level deprecation on snake_case fallback - Remove printWarningLogOnce — all deprecation warnings now fire on every request via printWarningLog - Add DEPRECATED_SKYFLOW_ID_REQUEST_KEY log entry for request-side key deprecation Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Revert "docs: add v2.1.0 upgrade banner and migration guide to v1 README (#310)" (#311) This reverts commit 6727625. * feat: prefer skyflowId over skyflow_id in UpdateRequest with deprecation warning When both keys are present, skyflowId is used and a warning is emitted. Adds unit tests for all four cases: camelCase only, snake_case only, both keys (preference), and both keys (map cleanup). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat: add getByot() as canonical form; keep getBYOT() as deprecated delegate - TokenMode.getByot() is the new preferred accessor; getBYOT() retained as @deprecated(since="2.1",forRemoval=true) delegate for back-compat - VaultClient updated to call getByot() at all three insert/update sites - UpdateTests: 5 new tests covering camelCase skyflowId key in UpdateRequest - LogUtilLevelTests: 5 new tests verifying WARN log fires at DEBUG/INFO/WARN levels and is suppressed at ERROR (matches Skyflow default) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test: add TokenModeTest covering getByot(), deprecated getBYOT() delegate, and toString() Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat: emit runtime deprecation warning in getBYOT(); test that it fires - InfoLogs: add DEPRECATED_GET_BYOT constant - TokenMode.getBYOT(): call LogUtil.printWarningLog() so callers see a runtime warning (consistent with downloadURL() and other deprecated methods) - TokenModeTest: replace @SuppressWarnings-only tests with assertions that the warning fires at INFO level and is suppressed at ERROR level Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor: consolidate both-keys deprecation warning into DEPRECATED_SKYFLOW_ID_REQUEST_KEY Remove DEPRECATED_SKYFLOW_ID_BOTH_KEYS; both the snake_case-only and both-keys-present paths in extractUpdateSkyflowId now emit the same DEPRECATED_SKYFLOW_ID_REQUEST_KEY message. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
1 parent d2cc3ab commit e7b5167

10 files changed

Lines changed: 410 additions & 20 deletions

File tree

‎src/main/java/com/skyflow/VaultClient.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest r
144144
.tokenization(request.getReturnTokens())
145145
.homogeneous(request.getHomogeneous())
146146
.upsert(request.getUpsert())
147-
.byot(request.getTokenMode().getBYOT())
147+
.byot(request.getTokenMode().getByot())
148148
.records(records)
149149
.build();
150150
}
@@ -171,14 +171,14 @@ protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertReques
171171

172172
return RecordServiceBatchOperationBody.builder()
173173
.continueOnError(true)
174-
.byot(request.getTokenMode().getBYOT())
174+
.byot(request.getTokenMode().getByot())
175175
.records(records)
176176
.build();
177177
}
178178

179179
protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest request) {
180180
RecordServiceUpdateRecordBody.Builder updateRequestBodyBuilder = RecordServiceUpdateRecordBody.builder();
181-
updateRequestBodyBuilder.byot(request.getTokenMode().getBYOT());
181+
updateRequestBodyBuilder.byot(request.getTokenMode().getByot());
182182
updateRequestBodyBuilder.tokenization(request.getReturnTokens());
183183
V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder();
184184
HashMap<String, Object> values = request.getData();

‎src/main/java/com/skyflow/enums/TokenMode.java‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.skyflow.enums;
22

33
import com.skyflow.generated.rest.types.V1Byot;
4+
import com.skyflow.logs.InfoLogs;
5+
import com.skyflow.utils.logger.LogUtil;
46

57
public enum TokenMode {
68
DISABLE(V1Byot.DISABLE),
@@ -13,10 +15,17 @@ public enum TokenMode {
1315
this.byot = byot;
1416
}
1517

16-
public V1Byot getBYOT() {
18+
public V1Byot getByot() {
1719
return byot;
1820
}
1921

22+
/** @deprecated Use {@link #getByot()} instead. */
23+
@Deprecated(since = "2.1", forRemoval = true)
24+
public V1Byot getBYOT() {
25+
LogUtil.printWarningLog(InfoLogs.DEPRECATED_GET_BYOT.getLog());
26+
return getByot();
27+
}
28+
2029
@Override
2130
public String toString() {
2231
return byot.toString();

‎src/main/java/com/skyflow/logs/InfoLogs.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,9 @@ public enum InfoLogs {
9898

9999
// Deprecation warnings — v2 backward compat
100100
DEPRECATED_SKYFLOW_ID_KEY("[DEPRECATED] Response key 'skyflow_id' is deprecated and will be removed in an upcoming release. Use 'skyflowId' instead."),
101-
DEPRECATED_DOWNLOAD_URL("[DEPRECATED] Method 'downloadURL()' is deprecated and will be removed in an upcoming release. Use 'downloadUrl()' instead.");
101+
DEPRECATED_SKYFLOW_ID_REQUEST_KEY("[DEPRECATED] Request data key 'skyflow_id' is deprecated and will be removed in an upcoming release. Use 'skyflowId' instead."),
102+
DEPRECATED_DOWNLOAD_URL("[DEPRECATED] Method 'downloadURL()' is deprecated and will be removed in an upcoming release. Use 'downloadUrl()' instead."),
103+
DEPRECATED_GET_BYOT("[DEPRECATED] Method 'getBYOT()' is deprecated and will be removed in an upcoming release. Use 'getByot()' instead.");
102104

103105

104106

‎src/main/java/com/skyflow/utils/logger/LogUtil.java‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,12 @@
44
import com.skyflow.logs.InfoLogs;
55
import com.skyflow.utils.Constants;
66

7-
import java.util.Collections;
8-
import java.util.Set;
9-
import java.util.concurrent.ConcurrentHashMap;
107
import java.util.logging.*;
118

129
public final class LogUtil {
1310
private static final Logger LOGGER = Logger.getLogger(LogUtil.class.getName());
1411
private static final String SDK_LOG_PREFIX = "[" + Constants.SDK_PREFIX + "] ";
1512
private static boolean isLoggerSetupDone = false;
16-
private static final Set<String> WARNED_ONCE = Collections.newSetFromMap(new ConcurrentHashMap<>());
1713

1814
synchronized public static void setupLogger(LogLevel logLevel) {
1915
isLoggerSetupDone = true;
@@ -60,11 +56,6 @@ public static void printWarningLog(String message) {
6056
LOGGER.warning(SDK_LOG_PREFIX + message);
6157
}
6258

63-
public static void printWarningLogOnce(String message) {
64-
if (isLoggerSetupDone && WARNED_ONCE.add(message))
65-
LOGGER.warning(SDK_LOG_PREFIX + message);
66-
}
67-
6859
public static void printInfoLog(String message) {
6960
if (isLoggerSetupDone)
7061
LOGGER.info(SDK_LOG_PREFIX + message);

‎src/main/java/com/skyflow/utils/validations/Validations.java‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -548,17 +548,17 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky
548548
ErrorLogs.EMPTY_DATA.getLog(), InterfaceName.UPDATE.getName()
549549
));
550550
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyData.getMessage());
551-
} else if (!data.containsKey("skyflow_id")) {
551+
} else if (!data.containsKey("skyflowId") && !data.containsKey("skyflow_id")) {
552552
LogUtil.printErrorLog(Utils.parameterizedString(
553553
ErrorLogs.SKYFLOW_ID_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName()
554554
));
555555
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.SkyflowIdKeyError.getMessage());
556-
} else if (!(data.get("skyflow_id") instanceof String)) {
556+
} else if (!(resolveUpdateId(data) instanceof String)) {
557557
LogUtil.printErrorLog(Utils.parameterizedString(
558558
ErrorLogs.INVALID_SKYFLOW_ID_TYPE.getLog(), InterfaceName.UPDATE.getName()
559559
));
560560
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidSkyflowIdType.getMessage());
561-
} else if (data.get("skyflow_id").toString().trim().isEmpty()) {
561+
} else if (resolveUpdateId(data).toString().trim().isEmpty()) {
562562
LogUtil.printErrorLog(Utils.parameterizedString(
563563
ErrorLogs.EMPTY_SKYFLOW_ID.getLog(), InterfaceName.UPDATE.getName()
564564
));
@@ -973,6 +973,13 @@ public static void validateDeidentifyFileRequest(DeidentifyFileRequest request)
973973
}
974974
}
975975

976+
static Object resolveUpdateId(HashMap<String, Object> data) {
977+
if (data.containsKey("skyflowId")) {
978+
return data.get("skyflowId");
979+
}
980+
return data.get("skyflow_id");
981+
}
982+
976983
public static void validateGetDetectRunRequest(GetDetectRunRequest request) throws SkyflowException {
977984
if (request == null) {
978985
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage());

‎src/main/java/com/skyflow/vault/controller/VaultController.java‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,18 @@ public VaultController(VaultConfig vaultConfig, Credentials credentials) {
8181
super(vaultConfig, credentials);
8282
}
8383

84+
private static String extractUpdateSkyflowId(HashMap<String, Object> data) {
85+
if (data.containsKey("skyflowId")) {
86+
if (data.containsKey("skyflow_id")) {
87+
data.remove("skyflow_id");
88+
LogUtil.printWarningLog(InfoLogs.DEPRECATED_SKYFLOW_ID_REQUEST_KEY.getLog());
89+
}
90+
return data.remove("skyflowId").toString();
91+
}
92+
LogUtil.printWarningLog(InfoLogs.DEPRECATED_SKYFLOW_ID_REQUEST_KEY.getLog());
93+
return data.remove("skyflow_id").toString();
94+
}
95+
8496
private static synchronized HashMap<String, Object> getFormattedBatchInsertRecord(Object record, Integer requestIndex) {
8597
HashMap<String, Object> insertRecord = new HashMap<>();
8698
String jsonString = GSON.toJson(record);
@@ -133,7 +145,7 @@ private static synchronized HashMap<String, Object> getFormattedGetRecord(V1Fiel
133145

134146
if (getRecord.containsKey("skyflow_id")) {
135147
getRecord.put("skyflowId", getRecord.get("skyflow_id"));
136-
LogUtil.printWarningLogOnce(InfoLogs.DEPRECATED_SKYFLOW_ID_KEY.getLog());
148+
LogUtil.printWarningLog(InfoLogs.DEPRECATED_SKYFLOW_ID_KEY.getLog());
137149
}
138150

139151
return getRecord;
@@ -158,7 +170,7 @@ private static synchronized HashMap<String, Object> getFormattedQueryRecord(V1Fi
158170

159171
if (queryRecord.containsKey("skyflow_id")) {
160172
queryRecord.put("skyflowId", queryRecord.get("skyflow_id"));
161-
LogUtil.printWarningLogOnce(InfoLogs.DEPRECATED_SKYFLOW_ID_KEY.getLog());
173+
LogUtil.printWarningLog(InfoLogs.DEPRECATED_SKYFLOW_ID_KEY.getLog());
162174
}
163175

164176
return queryRecord;
@@ -336,7 +348,7 @@ public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowExceptio
336348
result = super.getRecordsApi().recordServiceUpdateRecord(
337349
super.getVaultConfig().getVaultId(),
338350
updateRequest.getTable(),
339-
updateRequest.getData().remove("skyflow_id").toString(),
351+
extractUpdateSkyflowId(updateRequest.getData()),
340352
updateBody,
341353
requestOptions
342354
);
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
package com.skyflow.enums;
2+
3+
import com.skyflow.enums.LogLevel;
4+
import com.skyflow.generated.rest.types.V1Byot;
5+
import com.skyflow.logs.InfoLogs;
6+
import com.skyflow.utils.logger.LogUtil;
7+
import org.junit.Assert;
8+
import org.junit.Test;
9+
10+
import java.util.ArrayList;
11+
import java.util.List;
12+
import java.util.logging.Handler;
13+
import java.util.logging.Level;
14+
import java.util.logging.LogRecord;
15+
import java.util.logging.Logger;
16+
17+
public class TokenModeTest {
18+
19+
private static class CapturingHandler extends Handler {
20+
final List<LogRecord> records = new ArrayList<>();
21+
@Override public void publish(LogRecord r) { records.add(r); }
22+
@Override public void flush() {}
23+
@Override public void close() {}
24+
}
25+
26+
private CapturingHandler attachCapture() {
27+
CapturingHandler handler = new CapturingHandler();
28+
handler.setLevel(Level.ALL);
29+
Logger.getLogger(LogUtil.class.getName()).addHandler(handler);
30+
return handler;
31+
}
32+
33+
// --- getByot() ---
34+
35+
@Test
36+
public void testGetByotDisable() {
37+
Assert.assertEquals(V1Byot.DISABLE, TokenMode.DISABLE.getByot());
38+
}
39+
40+
@Test
41+
public void testGetByotEnable() {
42+
Assert.assertEquals(V1Byot.ENABLE, TokenMode.ENABLE.getByot());
43+
}
44+
45+
@Test
46+
public void testGetByotEnableStrict() {
47+
Assert.assertEquals(V1Byot.ENABLE_STRICT, TokenMode.ENABLE_STRICT.getByot());
48+
}
49+
50+
// --- getBYOT() delegates and emits a runtime warning ---
51+
52+
@Test
53+
@SuppressWarnings("deprecation")
54+
public void testGetBYOTDelegatesToGetByotDisable() {
55+
Assert.assertEquals(V1Byot.DISABLE, TokenMode.DISABLE.getBYOT());
56+
}
57+
58+
@Test
59+
@SuppressWarnings("deprecation")
60+
public void testGetBYOTDelegatesToGetByotEnable() {
61+
Assert.assertEquals(V1Byot.ENABLE, TokenMode.ENABLE.getBYOT());
62+
}
63+
64+
@Test
65+
@SuppressWarnings("deprecation")
66+
public void testGetBYOTDelegatesToGetByotEnableStrict() {
67+
Assert.assertEquals(V1Byot.ENABLE_STRICT, TokenMode.ENABLE_STRICT.getBYOT());
68+
}
69+
70+
@Test
71+
@SuppressWarnings("deprecation")
72+
public void testGetBYOTEmitsDeprecationWarning() {
73+
LogUtil.setupLogger(LogLevel.INFO);
74+
CapturingHandler handler = attachCapture();
75+
76+
TokenMode.ENABLE.getBYOT();
77+
78+
boolean warnFired = handler.records.stream()
79+
.anyMatch(r -> r.getLevel().equals(Level.WARNING)
80+
&& r.getMessage().contains(InfoLogs.DEPRECATED_GET_BYOT.getLog()));
81+
Assert.assertTrue("getBYOT() should emit a deprecation warning log", warnFired);
82+
}
83+
84+
@Test
85+
@SuppressWarnings("deprecation")
86+
public void testGetBYOTWarningIsSuppressedAtErrorLevel() {
87+
LogUtil.setupLogger(LogLevel.ERROR);
88+
CapturingHandler handler = attachCapture();
89+
90+
TokenMode.ENABLE.getBYOT();
91+
92+
boolean warnFired = handler.records.stream()
93+
.anyMatch(r -> r.getLevel().equals(Level.WARNING));
94+
Assert.assertFalse("getBYOT() warning should be suppressed at ERROR log level", warnFired);
95+
}
96+
97+
// --- toString() ---
98+
99+
@Test
100+
public void testToStringDisable() {
101+
Assert.assertEquals("DISABLE", TokenMode.DISABLE.toString());
102+
}
103+
104+
@Test
105+
public void testToStringEnable() {
106+
Assert.assertEquals("ENABLE", TokenMode.ENABLE.toString());
107+
}
108+
109+
@Test
110+
public void testToStringEnableStrict() {
111+
Assert.assertEquals("ENABLE_STRICT", TokenMode.ENABLE_STRICT.toString());
112+
}
113+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package com.skyflow.utils.logger;
2+
3+
import com.skyflow.enums.LogLevel;
4+
import org.junit.Assert;
5+
import org.junit.Test;
6+
7+
import java.util.ArrayList;
8+
import java.util.List;
9+
import java.util.logging.Handler;
10+
import java.util.logging.Level;
11+
import java.util.logging.LogRecord;
12+
import java.util.logging.Logger;
13+
14+
public class LogUtilLevelTests {
15+
16+
private static class CapturingHandler extends Handler {
17+
final List<LogRecord> records = new ArrayList<>();
18+
19+
@Override
20+
public void publish(LogRecord record) {
21+
records.add(record);
22+
}
23+
24+
@Override public void flush() {}
25+
@Override public void close() {}
26+
}
27+
28+
// setupLogger calls LogManager.reset() which clears all handlers,
29+
// so the capturing handler must be attached after setupLogger runs.
30+
private CapturingHandler attachCapture() {
31+
CapturingHandler handler = new CapturingHandler();
32+
handler.setLevel(Level.ALL);
33+
Logger.getLogger(LogUtil.class.getName()).addHandler(handler);
34+
return handler;
35+
}
36+
37+
@Test
38+
public void testWarnLogAppearsWhenLogLevelIsInfo() {
39+
LogUtil.setupLogger(LogLevel.INFO);
40+
CapturingHandler handler = attachCapture();
41+
42+
LogUtil.printWarningLog("deprecation warning");
43+
44+
boolean warnCaptured = handler.records.stream()
45+
.anyMatch(r -> r.getLevel().equals(Level.WARNING)
46+
&& r.getMessage().contains("deprecation warning"));
47+
Assert.assertTrue("WARN log should appear when LogLevel is INFO", warnCaptured);
48+
}
49+
50+
@Test
51+
public void testWarnLogAppearsWhenLogLevelIsWarn() {
52+
LogUtil.setupLogger(LogLevel.WARN);
53+
CapturingHandler handler = attachCapture();
54+
55+
LogUtil.printWarningLog("warn level warning");
56+
57+
boolean warnCaptured = handler.records.stream()
58+
.anyMatch(r -> r.getLevel().equals(Level.WARNING)
59+
&& r.getMessage().contains("warn level warning"));
60+
Assert.assertTrue("WARN log should appear when LogLevel is WARN", warnCaptured);
61+
}
62+
63+
@Test
64+
public void testWarnLogAppearsWhenLogLevelIsDebug() {
65+
LogUtil.setupLogger(LogLevel.DEBUG);
66+
CapturingHandler handler = attachCapture();
67+
68+
LogUtil.printWarningLog("debug level warning");
69+
70+
boolean warnCaptured = handler.records.stream()
71+
.anyMatch(r -> r.getLevel().equals(Level.WARNING)
72+
&& r.getMessage().contains("debug level warning"));
73+
Assert.assertTrue("WARN log should appear when LogLevel is DEBUG", warnCaptured);
74+
}
75+
76+
@Test
77+
public void testWarnLogSuppressedWhenLogLevelIsError() {
78+
LogUtil.setupLogger(LogLevel.ERROR);
79+
CapturingHandler handler = attachCapture();
80+
81+
LogUtil.printWarningLog("suppressed warning");
82+
83+
boolean warnCaptured = handler.records.stream()
84+
.anyMatch(r -> r.getLevel().equals(Level.WARNING));
85+
Assert.assertFalse("WARN log should NOT appear when LogLevel is ERROR", warnCaptured);
86+
}
87+
88+
@Test
89+
public void testInfoLogSuppressedWhenLogLevelIsWarn() {
90+
LogUtil.setupLogger(LogLevel.WARN);
91+
CapturingHandler handler = attachCapture();
92+
93+
LogUtil.printInfoLog("info message");
94+
95+
boolean infoCaptured = handler.records.stream()
96+
.anyMatch(r -> r.getLevel().equals(Level.INFO));
97+
Assert.assertFalse("INFO log should NOT appear when LogLevel is WARN", infoCaptured);
98+
}
99+
}

0 commit comments

Comments
 (0)