### Set User Properties (No Overwrite) in Java Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Use `userSetOnce` to set user profile properties only if they have not been set before. This is ideal for capturing initial values like the first referral source or sign-up date. ```java Map firstSeenProps = new HashMap<>(); firstSeenProps.put("first_referrer", "google"); firstSeenProps.put("first_seen_date", new Date()); try { td.userSetOnce("account_001", "device_abc", firstSeenProps); // Subsequent calls with the same keys are silently ignored by TE } catch (InvalidArgumentException e) { System.err.println("userSetOnce failed: " + e.getMessage()); } ``` -------------------------------- ### Initialize TDAnalytics with Strict Mode and UUID Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Initializes the SDK with strict mode for server-side data format verification and UUID mode for event deduplication. Recommended for production data quality. ```java // Strict mode ON + UUID ON — recommended for production data quality TDAnalytics td = new TDAnalytics(consumer, /*enableUUID=*/ true, /*isStrictModel=*/ true); try { // This will throw because eventName is empty in strict mode td.track("account_001", "device_abc", "", null); } catch (InvalidArgumentException e) { System.err.println(e.getMessage()); // "The event name must be provided." } try { // This will throw because a property key is invalid in strict mode Map badProps = new HashMap<>(); badProps.put("123invalid", "value"); // keys must start with a letter or # td.track("account_001", "device_abc", "test_event", badProps); } catch (InvalidArgumentException e) { System.err.println(e.getMessage()); // "Invalid key format: 123invalid" } ``` -------------------------------- ### Set, Track, and Manage Super Properties in Java Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Use `setSuperProperties` to attach properties to all subsequent events. Properties can be removed with `unsetSuperProperties` or `clearSuperProperties`. The `track` method sends an event, automatically including super properties. ```java // Set properties that apply to every event from this TDAnalytics instance td.setSuperProperties(new HashMap() {{ put("app_version", "4.2.1"); put("platform", "server"); put("env", "production"); }}); // Normal track — "app_version", "platform", and "env" are included automatically td.track("account_001", "device_abc", "api_call", new HashMap() {{ put("endpoint", "/v1/orders"); put("latency_ms", 87); }}); // Inspect current super properties Map current = td.getSuperProperties(); System.out.println(current); // {app_version=4.2.1, platform=server, env=production} // Remove a single key td.unsetSuperProperties("env"); // Remove all super properties td.clearSuperProperties(); ``` -------------------------------- ### flush / close Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Manages the SDK's lifecycle by flushing buffered events and closing resources. ```APIDOC ## Lifecycle Management ### `flush` / `close` #### Description `flush()` forces immediate delivery of all buffered events. `close()` calls `flush()`, stops background timers, and releases all I/O resources. Always call `close()` during application shutdown. #### Method - `flush()` - `close()` #### Parameters None #### Request Example ```java // Register a JVM shutdown hook for graceful drain Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { td.flush(); // send remaining buffered events } finally { td.close(); // release HTTP connections / file handles } })); ``` #### Response N/A (These are lifecycle management methods.) ``` -------------------------------- ### Manage SDK Lifecycle with flush and close Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Forces immediate delivery of buffered events with `flush()` and releases resources with `close()`. It is recommended to call `close()` during application shutdown, typically via a JVM shutdown hook. ```java // Register a JVM shutdown hook for graceful drain Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { td.flush(); // send remaining buffered events } finally { td.close(); // release HTTP connections / file handles } })); ``` -------------------------------- ### Track a Standard Event with Properties Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Records a user action. Either accountId or distinctId must be non-null. Special properties like '#time' and '#ip' can override event timestamp and IP for geo-resolution. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.exception.InvalidArgumentException; import java.util.Date; import java.util.HashMap; import java.util.Map; TDAnalytics td = new TDAnalytics(consumer, /*enableUUID=*/ true); Map props = new HashMap<>(); props.put("category", "electronics"); props.put("item_id", "sku_42"); props.put("price", 299.99); props.put("currency", "USD"); props.put("#time", new Date()); // override event timestamp (special "#" prefix) props.put("#ip", "203.0.113.42"); // override IP for geo-resolution try { td.track( "account_001", // accountId (logged-in user ID; null OK if distinctId is set) "device_abc", // distinctId (anonymous device/session ID; null OK if accountId is set) "add_to_cart", // eventName — alphanumeric + underscore, max 50 chars props ); } catch (InvalidArgumentException e) { System.err.println("Bad event data: " + e.getMessage()); } ``` -------------------------------- ### Set Dynamic Super Properties Tracker in Java Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Implement `DynamicSuperPropertiesTracker` to attach computed properties that change over time to every event. The `getDynamicSuperProperties()` method is invoked for each event. ```java import cn.thinkingdata.analytics.inter.DynamicSuperPropertiesTracker; td.setDynamicSuperPropertiesTracker(new DynamicSuperPropertiesTracker() { @Override public Map getDynamicSuperProperties() { Map dynamic = new HashMap<>(); dynamic.put("session_id", SessionManager.getCurrentSessionId()); // evaluated at event time dynamic.put("ab_group", ABTestService.getGroupForCurrentUser()); return dynamic; } }); // Every subsequent track call will include session_id and ab_group at the time of the call td.track("account_001", "device_abc", "checkout_started", null); ``` -------------------------------- ### track — Report a standard event Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Records a user action. Either `accountId` or `distinctId` must be non-null; both can be supplied for identity stitching. ```APIDOC ## track ### Description Records a user action. Either `accountId` or `distinctId` must be non-null; both can be supplied for identity stitching. ### Method Signature ```java td.track(String accountId, String distinctId, String eventName, Map properties) ``` ### Parameters * **accountId** (String) - The ID of the logged-in user. Can be null if `distinctId` is set. * **distinctId** (String) - The ID of the anonymous device or session. Can be null if `accountId` is set. * **eventName** (String) - The name of the event. Must be alphanumeric and underscore, max 50 characters. * **properties** (Map) - A map of event properties. Special properties like `#time` and `#ip` can be used to override defaults. ### Request Example ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.exception.InvalidArgumentException; import java.util.Date; import java.util.HashMap; import java.util.Map; TDAnalytics td = new TDAnalytics(consumer, /*enableUUID=*/ true); Map props = new HashMap<>(); props.put("category", "electronics"); props.put("item_id", "sku_42"); props.put("price", 299.99); props.put("currency", "USD"); props.put("#time", new Date()); // override event timestamp (special "#" prefix) props.put("#ip", "203.0.113.42"); // override IP for geo-resolution try { td.track( "account_001", // accountId "device_abc", // distinctId "add_to_cart", // eventName props ); } catch (InvalidArgumentException e) { System.err.println("Bad event data: " + e.getMessage()); } ``` ``` -------------------------------- ### TDAnalytics Constructor Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Advanced constructor for initializing TDAnalytics with options for strict mode and UUID generation. ```APIDOC ## Advanced Constructor ### `TDAnalytics(consumer, enableUUID, isStrictModel)` #### Description Initializes the TDAnalytics SDK with options for server-side data format verification (strict mode) and automatic UUID generation for event deduplication. #### Method `TDAnalytics(ITDAnalyticsConsumer consumer, boolean enableUUID, boolean isStrictModel)` #### Parameters - **consumer** (ITDAnalyticsConsumer) - Required - The consumer strategy for event delivery. - **enableUUID** (boolean) - Required - If true, auto-generates a `#uuid` (v4) for each event, enabling exactly-once deduplication. - **isStrictModel** (boolean) - Required - If true, enables server-side data format verification (key naming rules, type constraints, mandatory fields). #### Request Example ```java // Strict mode ON + UUID ON — recommended for production data quality TDAnalytics td = new TDAnalytics(consumer, /*enableUUID=*/ true, /*isStrictModel=*/ true); try { // This will throw because eventName is empty in strict mode td.track("account_001", "device_abc", "", null); } catch (InvalidArgumentException e) { System.err.println(e.getMessage()); // "The event name must be provided." } try { // This will throw because a property key is invalid in strict mode Map badProps = new HashMap<>(); badProps.put("123invalid", "value"); // keys must start with a letter or # td.track("account_001", "device_abc", "test_event", badProps); } catch (InvalidArgumentException e) { System.err.println(e.getMessage()); // "Invalid key format: 123invalid" } ``` #### Response N/A (This is a constructor.) #### Error Handling - **InvalidArgumentException**: Thrown when data validation fails in strict mode. ``` -------------------------------- ### TDAnalytics.enableLog / TDAnalytics.setLogger Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Enables or replaces the SDK's internal logger. By default, logging is disabled. ```APIDOC ## Logging Control ### `TDAnalytics.enableLog` / `TDAnalytics.setLogger` #### Description Enables or replaces the SDK's internal logger. By default, logging is disabled (except in `TDDebugConsumer`). #### Method - `enableLog(boolean enabled)` - `setLogger(ITDLogger logger)` #### Parameters - `enabled` (boolean) - Required - Whether to enable the default stdout logger. - `logger` (ITDLogger) - Required - An instance of a custom logger implementing the `ITDLogger` interface. #### Request Example ```java // Enable the default stdout logger TDAnalytics.enableLog(true); // Plug in a custom logger (e.g., SLF4J) TDAnalytics.setLogger(new ITDLogger() { private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("ThinkingDataSDK"); @Override public void log(String msg) { log.debug(msg); } }); ``` #### Response N/A (These are configuration methods.) ``` -------------------------------- ### Configure TDBatchConsumer for HTTP Batch Delivery Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Configure TDBatchConsumer for direct HTTP delivery to the TE server. Adjust batch size, timeout, auto-flush, compression, cache size, and exception handling. Ensure the TE receiver URL, App ID, and shutdown procedures are correctly implemented. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.TDBatchConsumer; // Fine-grained configuration TDBatchConsumer.Config config = new TDBatchConsumer.Config(); config.setBatchSize(50); // flush every 50 events (default: 20, max: 1000) config.setTimeout(30000); // HTTP timeout in ms (default: 30 000) config.setAutoFlush(true); // enable periodic background flush config.setInterval(5); // flush interval in seconds (default: 3) config.setCompress("gzip"); // "gzip" (default) or "none" config.setMaxCacheSize(100); // max pending batches before oldest is dropped (default: 50) config.setThrowException(true); // surface HTTP errors as exceptions (default: false) TDBatchConsumer consumer = new TDBatchConsumer( "https://receiver.example.com", // TE receiver URL "your-app-id", // Project App ID from TE dashboard config ); TDAnalytics td = new TDAnalytics(consumer, /*enableUUID=*/ true); // ... use td ... td.flush(); // drain all buffered events before shutdown td.close(); // stops the auto-flush timer and closes the HTTP connection pool ``` -------------------------------- ### Configure TDLoggerConsumer for Local Log Files Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Configure TDLoggerConsumer to write newline-delimited JSON records to local files for LogBus2 agent consumption. Customize log directory, filename prefix, rotation mode, file size limits, buffer size, auto-flush, interval, and optional lock file for multi-process safety. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.TDLoggerConsumer; TDLoggerConsumer.Config config = new TDLoggerConsumer.Config("./td_logs"); // log directory (created if absent) config.setFilenamePrefix("app"); // files: app.log.yyyy-MM-dd_0 config.setRotateMode(TDLoggerConsumer.RotateMode.HOURLY); // DAILY (default) or HOURLY rotation config.setFileSize(512); // max single file size in MB (0 = unlimited) config.setBufferSize(16384); // write buffer in bytes (default: 8192) config.setAutoFlush(true); // enable periodic background flush config.setInterval(5); // flush interval in seconds config.setLockFile("/tmp/td_sdk.lock"); // optional external lock file for multi-process safety TDLoggerConsumer consumer = new TDLoggerConsumer(config); TDAnalytics td = new TDAnalytics(consumer); td.track("account_001", "device_abc", "page_view", new HashMap() {{ put("page", "/home"); put("referrer", "google"); }}); td.flush(); // flush buffer to disk td.close(); // final flush + close file handles ``` -------------------------------- ### Super Properties Management Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Manage properties that are automatically attached to every event. This includes setting, unsetting, clearing, and tracking dynamic super properties. ```APIDOC ## setSuperProperties / unsetSuperProperties / clearSuperProperties — Attach properties to every event Super properties are merged into every subsequent `track*` call automatically. They are stored in a thread-safe `ConcurrentHashMap`. ```java // Set properties that apply to every event from this TDAnalytics instance td.setSuperProperties(new HashMap() {{ put("app_version", "4.2.1"); put("platform", "server"); put("env", "production"); }}); // Normal track — "app_version", "platform", and "env" are included automatically td.track("account_001", "device_abc", "api_call", new HashMap() {{ put("endpoint", "/v1/orders"); put("latency_ms", 87); }}); // Inspect current super properties Map current = td.getSuperProperties(); System.out.println(current); // {app_version=4.2.1, platform=server, env=production} // Remove a single key td.unsetSuperProperties("env"); // Remove all super properties td.clearSuperProperties(); ``` ## setDynamicSuperPropertiesTracker — Attach computed properties to every event The tracker's `getDynamicSuperProperties()` is called on each event, allowing values that change over time (e.g., session ID, A/B test assignment) to be appended without rebuilding static super properties. ```java import cn.thinkingdata.analytics.inter.DynamicSuperPropertiesTracker; td.setDynamicSuperPropertiesTracker(new DynamicSuperPropertiesTracker() { @Override public Map getDynamicSuperProperties() { Map dynamic = new HashMap<>(); dynamic.put("session_id", SessionManager.getCurrentSessionId()); // evaluated at event time dynamic.put("ab_group", ABTestService.getGroupForCurrentUser()); return dynamic; } }); // Every subsequent track call will include session_id and ab_group at the time of the call td.track("account_001", "device_abc", "checkout_started", null); ``` ``` -------------------------------- ### Increment Numeric User Properties in Java Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Use `userAdd` to increment numeric user profile properties by a specified delta. Only `Number` values are accepted; non-numeric values will cause an exception in strict mode. ```java Map increments = new HashMap<>(); increments.put("purchase_count", 1); increments.put("lifetime_spend", 29.99); increments.put("login_count", 1); try { td.userAdd("account_001", "device_abc", increments); } catch (InvalidArgumentException e) { System.err.println("userAdd failed: " + e.getMessage()); } ``` -------------------------------- ### User Profile Operations Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Operations for managing user profile properties, including setting, incrementing, appending, and unsetting properties. ```APIDOC ## userSet — Set user properties (overwrite) Sets user profile properties, overwriting any existing values for the given keys. ```java Map profile = new HashMap<>(); profile.put("name", "Alice"); profile.put("email", "alice@example.com"); profile.put("plan", "pro"); profile.put("signup_date", new Date()); try { td.userSet("account_001", "device_abc", profile); } catch (InvalidArgumentException e) { System.err.println("userSet failed: " + e.getMessage()); } ``` ## userSetOnce — Set user properties (no overwrite) Sets user profile properties only if the property has not been set before. Useful for capturing first-ever values such as first seen date or initial referral source. ```java Map firstSeenProps = new HashMap<>(); firstSeenProps.put("first_referrer", "google"); firstSeenProps.put("first_seen_date", new Date()); try { td.userSetOnce("account_001", "device_abc", firstSeenProps); // Subsequent calls with the same keys are silently ignored by TE } catch (InvalidArgumentException e) { System.err.println("userSetOnce failed: " + e.getMessage()); } ``` ## userAdd — Increment numeric user properties Adds numeric delta values to existing user profile properties. Only `Number` values are accepted; a non-number value will throw `InvalidArgumentException` in strict mode. ```java Map increments = new HashMap<>(); increments.put("purchase_count", 1); increments.put("lifetime_spend", 29.99); increments.put("login_count", 1); try { td.userAdd("account_001", "device_abc", increments); } catch (InvalidArgumentException e) { System.err.println("userAdd failed: " + e.getMessage()); } ``` ## userAppend / userUniqAppend — Append to array-type user properties `userAppend` appends items to a list property. `userUniqAppend` does the same but deduplicates the list, ensuring each value appears at most once. ```java // Append tags (duplicates allowed) Map newTags = new HashMap<>(); newTags.put("tags", Arrays.asList("vip", "beta_tester")); td.userAppend("account_001", "device_abc", newTags); // Append categories (no duplicates) Map categories = new HashMap<>(); categories.put("viewed_categories", Arrays.asList("electronics", "books", "electronics")); // "electronics" will appear once try { td.userUniqAppend("account_001", "device_abc", categories); } catch (InvalidArgumentException e) { System.err.println("userUniqAppend failed: " + e.getMessage()); } ``` ## userUnset — Clear specific user properties Resets one or more user profile properties to null/empty. ```java try { td.userUnset("account_001", "device_abc", "email", "phone", "plan"); } catch (InvalidArgumentException e) { System.err.println("userUnset failed: " + e.getMessage()); } ``` ``` -------------------------------- ### Set User Properties (Overwrite) in Java Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Use `userSet` to set user profile properties, overwriting any existing values for the specified keys. This is useful for updating user information like name or email. ```java Map profile = new HashMap<>(); profile.put("name", "Alice"); profile.put("email", "alice@example.com"); profile.put("plan", "pro"); profile.put("signup_date", new Date()); try { td.userSet("account_001", "device_abc", profile); } catch (InvalidArgumentException e) { System.err.println("userSet failed: " + e.getMessage()); } ``` -------------------------------- ### trackFirst — Report a first-occurrence-only event Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt The event is recorded only once per unique `firstCheckId`. Subsequent reports with the same ID are de-duplicated by TE. ```APIDOC ## trackFirst ### Description Reports a first-occurrence-only event. The event is recorded only once per unique `firstCheckId`. Subsequent reports with the same ID are de-duplicated by TE. ### Method Signature ```java td.trackFirst(String accountId, String distinctId, String eventName, String firstCheckId, Map properties) ``` ### Parameters * **accountId** (String) - The ID of the logged-in user. * **distinctId** (String) - The ID of the anonymous device or session. * **eventName** (String) - The name of the event. * **firstCheckId** (String) - A unique identifier for the first occurrence of this event. Required. * **properties** (Map) - A map of event properties. ### Request Example ```java Map props = new HashMap<>(); props.put("platform", "android"); props.put("install_source", "organic"); try { td.trackFirst( "account_001", "device_abc", "first_launch", "device_abc_first_launch", // firstCheckId — unique per user/device; required props ); } catch (InvalidArgumentException e) { System.err.println("Error: " + e.getMessage()); } // Alternative: embed "#first_check_id" directly in the properties map props.put("#first_check_id", "device_abc_first_launch"); td.trackFirst("account_001", "device_abc", "first_launch", null, props); ``` ``` -------------------------------- ### Control SDK Logging with TDAnalytics Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Enables or replaces the SDK's internal logger. By default, logging is disabled. You can enable the default stdout logger or plug in a custom logger like SLF4J. ```java import cn.thinkingdata.analytics.inter.ITDLogger; // Enable the default stdout logger TDAnalytics.enableLog(true); // Plug in a custom logger (e.g., SLF4J) TDAnalytics.setLogger(new ITDLogger() { private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("ThinkingDataSDK"); @Override public void log(String msg) { log.debug(msg); } }); ``` -------------------------------- ### Initialize TDDebugConsumer for Development Validation Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Use TDDebugConsumer to send events one-by-one to the TE /data_debug endpoint for format validation. Set writeData to false for validation only (safe for CI) or true to validate and persist. Logging is automatically enabled. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.TDDebugConsumer; // writeData=false → validate only, do NOT persist to TE database (safe for CI) // writeData=true → validate AND persist (use to seed test data) TDDebugConsumer consumer = new TDDebugConsumer( "https://receiver.example.com", "your-app-id", /*writeData=*/ false, /*deviceId=*/ "dev-machine-001" // optional; identifies the debug device in TE UI ); TDAnalytics td = new TDAnalytics(consumer); TDAnalytics.enableLog(true); // already enabled by TDDebugConsumer, shown here for clarity try { td.track("account_001", "device_abc", "purchase", new HashMap() {{ put("item_id", "sku_42"); put("price", 9.99); }}); } catch (RuntimeException e) { // TDDebugConsumer throws on invalid JSON or HTTP error System.err.println("Validation failed: " + e.getMessage()); } td.close(); ``` -------------------------------- ### Track a First-Occurrence Event Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Records an event only once per unique `firstCheckId`. Subsequent reports with the same ID are de-duplicated. The `firstCheckId` is required and can also be embedded in the properties map as '#first_check_id'. ```java Map props = new HashMap<>(); props.put("platform", "android"); props.put("install_source", "organic"); try { td.trackFirst( "account_001", "device_abc", "first_launch", "device_abc_first_launch", // firstCheckId — unique per user/device; required props ); } catch (InvalidArgumentException e) { System.err.println("Error: " + e.getMessage()); } // Alternative: embed "#first_check_id" directly in the properties map props.put("#first_check_id", "device_abc_first_launch"); td.trackFirst("account_001", "device_abc", "first_launch", null, props); ``` -------------------------------- ### Append to Array User Properties in Java Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Use `userAppend` to add items to an array-type user property, allowing duplicates. Use `userUniqAppend` to append items while ensuring uniqueness within the array. ```java // Append tags (duplicates allowed) Map newTags = new HashMap<>(); newTags.put("tags", Arrays.asList("vip", "beta_tester")); td.userAppend("account_001", "device_abc", newTags); // Append categories (no duplicates) Map categories = new HashMap<>(); categories.put("viewed_categories", Arrays.asList("electronics", "books", "electronics")); // "electronics" will appear once try { td.userUniqAppend("account_001", "device_abc", categories); } catch (InvalidArgumentException e) { System.err.println("userUniqAppend failed: " + e.getMessage()); } ``` -------------------------------- ### userDelete Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Permanently deletes all profile properties for the specified user. This operation cannot be undone. ```APIDOC ## userDelete ### Description Permanently deletes all profile properties for the specified user. This operation cannot be undone. ### Method Not specified (assumed to be a method call on a TDAnalytics object) ### Endpoint Not applicable (SDK method) ### Parameters - **userId** (string) - Required - The unique identifier for the user. - **deviceId** (string) - Required - The unique identifier for the device. ### Request Example ```java td.userDelete("account_001", "device_abc"); ``` ### Response No specific response details provided, but exceptions may be thrown. #### Error Handling - **InvalidArgumentException**: Thrown if the provided arguments are invalid. ``` -------------------------------- ### Delete User Profile with TDAnalytics Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Permanently deletes all profile properties for a specified user. This operation is irreversible and requires valid account and device IDs. ```java try { td.userDelete("account_001", "device_abc"); } catch (InvalidArgumentException e) { System.err.println("userDelete failed: " + e.getMessage()); } ``` -------------------------------- ### Clear Specific User Properties in Java Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Use `userUnset` to reset one or more user profile properties to null or empty. This operation removes the specified properties from the user's profile. ```java try { td.userUnset("account_001", "device_abc", "email", "phone", "plan"); } catch (InvalidArgumentException e) { System.err.println("userUnset failed: " + e.getMessage()); } ``` -------------------------------- ### trackUpdate — Update an existing event's properties Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Merges new property values into a previously reported event identified by `eventId`. Properties not mentioned in the update are preserved. ```APIDOC ## trackUpdate ### Description Updates an existing event's properties. Merges new property values into a previously reported event identified by `eventId`. Properties not mentioned in the update are preserved. ### Method Signature ```java td.trackUpdate(String accountId, String distinctId, String eventName, String eventId, Map properties) ``` ### Parameters * **accountId** (String) - The ID of the logged-in user. * **distinctId** (String) - The ID of the anonymous device or session. * **eventName** (String) - The name of the event. * **eventId** (String) - The unique identifier of the event to update. * **properties** (Map) - A map of properties to update. ### Request Example ```java // Initial report Map initial = new HashMap<>(); initial.put("status", "started"); initial.put("duration_sec", 0); td.trackUpdate("account_001", "device_abc", "video_play", "session_789", initial); // Later — patch only the changed fields Map patch = new HashMap<>(); patch.put("status", "completed"); patch.put("duration_sec", 142); try { td.trackUpdate( "account_001", "device_abc", "video_play", "session_789", // same eventId → merges into the original record patch ); } catch (InvalidArgumentException e) { System.err.println("Update failed: " + e.getMessage()); } ``` ``` -------------------------------- ### trackOverwrite — Replace an event entirely Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Completely replaces all properties of a previously reported event identified by `eventId`. Unlike `trackUpdate`, properties absent from the new payload are removed. ```APIDOC ## trackOverwrite ### Description Replaces an event entirely. Completely replaces all properties of a previously reported event identified by `eventId`. Unlike `trackUpdate`, properties absent from the new payload are removed. ### Method Signature ```java td.trackOverwrite(String accountId, String distinctId, String eventName, String eventId, Map properties) ``` ### Parameters * **accountId** (String) - The ID of the logged-in user. * **distinctId** (String) - The ID of the anonymous device or session. * **eventName** (String) - The name of the event. * **eventId** (String) - The unique identifier of the event to overwrite. * **properties** (Map) - A map of the new properties for the event. ### Request Example ```java Map replacement = new HashMap<>(); replacement.put("status", "refunded"); replacement.put("amount", 0.0); replacement.put("reason", "customer_request"); try { td.trackOverwrite( "account_001", "device_abc", "purchase", "order_456", // eventId of the original purchase event replacement ); } catch (InvalidArgumentException e) { System.err.println("Overwrite failed: " + e.getMessage()); } ``` ``` -------------------------------- ### TDDebugConsumer - Development-time data validation Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt The TDDebugConsumer sends events one-by-one to the TE /data_debug endpoint for format validation and error reporting. It's intended for development and integration testing. Logging is automatically enabled. ```APIDOC ## TDDebugConsumer ### Description Sends events one-by-one to the TE `/data_debug` endpoint for data validation and returns detailed error messages. Logging is automatically enabled. Use this consumer only during development and integration testing. ### Usage ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.TDDebugConsumer; // writeData=false → validate only, do NOT persist to TE database (safe for CI) // writeData=true → validate AND persist (use to seed test data) TDDebugConsumer consumer = new TDDebugConsumer( "https://receiver.example.com", "your-app-id", /*writeData=*/ false, /*deviceId=*/ "dev-machine-001" // optional; identifies the debug device in TE UI ); TDAnalytics td = new TDAnalytics(consumer); TDAnalytics.enableLog(true); // already enabled by TDDebugConsumer, shown here for clarity try { td.track("account_001", "device_abc", "purchase", new HashMap() {{ put("item_id", "sku_42"); put("price", 9.99); }}); } catch (RuntimeException e) { // TDDebugConsumer throws on invalid JSON or HTTP error System.err.println("Validation failed: " + e.getMessage()); } td.close(); ``` ``` -------------------------------- ### Replace an Event Entirely Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Completely replaces all properties of a previously reported event identified by `eventId`. Unlike `trackUpdate`, properties absent from the new payload are removed. ```java Map replacement = new HashMap<>(); replacement.put("status", "refunded"); replacement.put("amount", 0.0); replacement.put("reason", "customer_request"); try { td.trackOverwrite( "account_001", "device_abc", "purchase", "order_456", // eventId of the original purchase event replacement ); } catch (InvalidArgumentException e) { System.err.println("Overwrite failed: " + e.getMessage()); } ``` -------------------------------- ### Update an Existing Event's Properties Source: https://context7.com/thinkingdataanalytics/java-sdk/llms.txt Merges new property values into a previously reported event identified by `eventId`. Properties not mentioned in the update are preserved. Use this to patch changed fields. ```java // Initial report Map initial = new HashMap<>(); initial.put("status", "started"); initial.put("duration_sec", 0); td.trackUpdate("account_001", "device_abc", "video_play", "session_789", initial); // Later — patch only the changed fields Map patch = new HashMap<>(); patch.put("status", "completed"); patch.put("duration_sec", 142); try { td.trackUpdate( "account_001", "device_abc", "video_play", "session_789", // same eventId → merges into the original record patch ); } catch (InvalidArgumentException e) { System.err.println("Update failed: " + e.getMessage()); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.