### Publish to Maven Central via Local Script Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/README.md Example of how to publish the library to Maven Central using a local script. Ensure all required environment variables are set. ```bash export MAVEN_CENTRAL_USERNAME=... export MAVEN_CENTRAL_PASSWORD=... export MAVEN_GPG_PRIVATE_KEY=... export MAVEN_GPG_PASSPHRASE=... ./scripts/publish-central.sh 1.2.3 ``` -------------------------------- ### Custom Template Source with JsonTemplateMapper Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/README.md Shows how to provide a custom TemplateRepository to JsonTemplateMapper for loading templates from non-standard sources. This example uses an in-memory JSON string as the template. ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import com.thanhlv.dynamicjsonmapper.TemplateRepository; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); TemplateRepository repository = new TemplateRepository() { @Override public JsonNode getTemplate(String templatePath) { try { return objectMapper.readTree("{\"message\": \"${message}\"}"); } catch (Exception e) { throw new RuntimeException(e); } } }; JsonTemplateMapper mapper = new JsonTemplateMapper(objectMapper, repository); JsonNode result = mapper.render("ignored", Map.of("${message}", "hello")); ``` -------------------------------- ### Get Default JsonTemplateMapper Instance Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Obtain a shared, lazily-initialized singleton mapper for application-wide use. This instance is backed by CachingClasspathTemplateRepository and is suitable when custom ObjectMapper or repository configurations are not required. ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import tools.jackson.databind.JsonNode; import java.util.Map; // Reuse the singleton — no allocation cost after first call JsonTemplateMapper mapper = JsonTemplateMapper.defaultInstance(); JsonNode result = mapper.render("templates/user-template.json", Map.of( "${name}", "Thanh", "${tuoi}", 23, "${noio}", "Hà Nội" )); // Template: templates/user-template.json // { // "status": "SUCCESS", // "data": { // "account_info": { "user_name": "${name}", "age": "${tuoi}" }, // "location_details": { "city": "${noio}", "country": "Việt Nam" } // }, // "metadata": { "server_id": "SV-01" } // } System.out.println(mapper.jsonNodeToString(result)); ``` -------------------------------- ### Build and Test DynamicJsonMapper Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/README.md Commands to clean, build, and test the DynamicJsonMapper project using Gradle. ```bash ./gradlew clean build ./gradlew test ./gradlew classes ``` -------------------------------- ### Run Specific Tests for DynamicJsonMapper Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/README.md Gradle commands to run specific test suites for DynamicJsonMapper, useful for targeted testing. ```bash ./gradlew test --tests com.thanhlv.dynamicjsonmapper.DynamicJsonMapperTest ./gradlew test --tests com.thanhlv.dynamicjsonmapper.DeepNestedMapperTest ./gradlew test --tests com.thanhlv.dynamicjsonmapper.PaginatedListMapperTest ``` -------------------------------- ### Render JSON from Template with Raw Data Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Load a JSON template from the classpath, replace placeholder tokens (e.g., `${key}`) with corresponding values from a provided Map, and return the rendered JsonNode. Ensure placeholder tokens match exactly. If a key is missing in the rawData map, the corresponding field will be rendered as JSON null. ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import tools.jackson.databind.JsonNode; import java.util.HashMap; import java.util.Map; JsonTemplateMapper mapper = JsonTemplateMapper.defaultInstance(); // Template: templates/deep-nested-template.json // { // "user_id": "${id}", // "profile": { // "display_name": "${name}", // "address": { "city": "${city}", "district": "${dist}", "detail": "${street}" } // }, // "expertise": { "main": "${skill_primary}", "rank": "${skill_level}" } // } Map rawData = Map.of( "${id}", "USR-99", "${name}", "Thanh", "${city}", "Hà Nội", "${dist}", "Cầu Giấy", "${street}", "Duy Tân", "${skill_primary}", "Java", "${skill_level}", "Senior" ); JsonNode response = mapper.render("templates/deep-nested-template.json", rawData); // Navigate the rendered tree String userId = response.path("user_id").asText(); // "USR-99" String city = response.path("profile").path("address").path("city").asText(); // "Hà Nội" String skill = response.path("expertise").path("main").asText(); // "Java" // Missing placeholder example — key not in rawData becomes null Map partial = new HashMap<>(); partial.put("${id}", "USR-00"); // "${name}", "${city}", ... not supplied → those fields render as null JsonNode partialResult = mapper.render("templates/deep-nested-template.json", partial); System.out.println(partialResult.path("profile").path("display_name").isNull()); // true ``` -------------------------------- ### Expand Child Templates with $template_ref and $source Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Use `$template_ref` to specify a child template and `$source` to bind data from rawData. When `$source` resolves to an array, the child template renders for each element, exposing its fields as placeholders. ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import tools.jackson.databind.JsonNode; import java.util.List; import java.util.Map; import java.util.HashMap; JsonTemplateMapper mapper = JsonTemplateMapper.defaultInstance(); List> users = List.of( Map.of("id", 1, "name", "An"), Map.of("id", 2, "name", "Binh"), Map.of("id", 3, "name", "Chi"), Map.of("id", 4, "name", "Dung"), Map.of("id", 5, "name", "Giang") ); // Simple pagination slice — page 2, size 2 → items [Chi, Dung] List> page2Items = users.subList(2, 4); Map rawData = new HashMap<>(); rawData.put("${page}", 2); rawData.put("${size}", 2); rawData.put("${total}", users.size()); rawData.put("${total_pages}", 3); rawData.put("${items}", page2Items); rawData.put("${first_item}", page2Items.get(0)); rawData.put("${last_item}", page2Items.get(page2Items.size() - 1)); JsonNode response = mapper.render("templates/paginated-users-template.json", rawData); System.out.println(response.path("status").asText()); // "SUCCESS" System.out.println(response.path("data").path("total").asInt()); // 5 System.out.println(response.path("data").path("items").size()); // 2 System.out.println(response.path("data").path("items").get(0).path("user_id").asInt()); // 3 System.out.println(response.path("data").path("items").get(0).path("display_name").asText()); // "Chi" System.out.println(response.path("data").path("first_item").path("display_name").asText()); // "Chi" System.out.println(response.path("data").path("last_item").path("display_name").asText()); // "Dung" ``` -------------------------------- ### JsonTemplateMapper.render(String templatePath, Map rawData) Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Loads a template from the specified classpath path, replaces all `${key}` placeholder tokens with corresponding values from the provided `rawData` map, and returns the fully rendered `JsonNode`. ```APIDOC ## JsonTemplateMapper.render(String templatePath, Map rawData) ### Description Loads a template from the specified classpath path, replaces all `${key}` placeholder tokens with corresponding values from the provided `rawData` map, and returns the fully rendered `JsonNode`. ### Parameters * **templatePath** (String): The classpath path to the JSON template file. * **rawData** (Map): A map where keys are the placeholder tokens (e.g., "${name}") and values are the data to substitute. ### Returns * **JsonNode**: The rendered JSON structure after placeholder replacement. ### Example ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import tools.jackson.databind.JsonNode; import java.util.Map; // Assume 'templates/user-template.json' exists on the classpath // and contains placeholders like "${name}", "${age}" Map data = Map.of( "${name}", "Thanh", "${age}", 23 ); JsonNode renderedJson = JsonTemplateMapper.render("templates/user-template.json", data); // renderedJson will contain the JSON with placeholders replaced System.out.println(renderedJson.toString()); ``` ### Error Handling * If the `templatePath` does not exist on the classpath, an exception will be thrown. * If a placeholder token exists in the template but not in the `rawData` map, it will be rendered as JSON `null`. ``` -------------------------------- ### Core Usage of JsonTemplateMapper Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/README.md Demonstrates the basic usage of JsonTemplateMapper to render a JSON template with provided data. Ensure the template file exists and data keys match placeholders. ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import tools.jackson.databind.JsonNode; import java.util.Map; JsonTemplateMapper mapper = JsonTemplateMapper.defaultInstance(); JsonNode output = mapper.render("templates/user-template.json", Map.of( "${name}", "Thanh", "${tuoi}", 23, "${noio}", "Ha Noi" )); String pretty = mapper.jsonNodeToString(output); ``` -------------------------------- ### JSON template rendering from classpath resources Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/docs/FEATURES.md Renders a JSON template by loading it from classpath resources. It recursively processes nested structures and replaces placeholder tokens with values from raw data. Missing keys result in JSON null. ```APIDOC ## JsonTemplateMapper#render(...) ### Description Loads a template JSON by its classpath path and recursively processes nested objects and arrays. It replaces textual placeholder tokens like `${key}` with values from the provided `rawData`. If a placeholder key is not found in `rawData`, the corresponding field in the output JSON will be `null`. ### Method `render(String templatePath, Map rawData)` ### Parameters #### Path Parameters - **templatePath** (String) - Required - The classpath path to the template JSON file. - **rawData** (Map) - Required - A map containing the data to be merged into the template. ### Response #### Success Response (JsonNode) - The rendered JSON structure as a `JsonNode`. ``` -------------------------------- ### Template repository abstraction and pluggable sources Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/docs/FEATURES.md Provides a `TemplateRepository` interface for custom template loading strategies. The default implementation is `CachingClasspathTemplateRepository`. Users can inject custom repositories and `ObjectMapper` instances into `JsonTemplateMapper`. ```APIDOC ## TemplateRepository Interface ### Description The `TemplateRepository` interface abstracts the mechanism for loading JSON templates. This allows for pluggable template sourcing strategies beyond the default classpath loading. The `JsonTemplateMapper` can be configured with a custom `TemplateRepository` implementation during instantiation, enabling flexible template management. ### Usage `JsonTemplateMapper` supports constructor injection of a custom `TemplateRepository` and/or a custom `ObjectMapper`. ``` -------------------------------- ### JsonTemplateMapper.defaultInstance() Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Returns a shared, lazily-initialized singleton mapper instance. This is the recommended way to obtain a mapper for application-wide use when custom configurations are not needed. ```APIDOC ## JsonTemplateMapper.defaultInstance() ### Description Returns a shared, lazily-initialized singleton mapper instance. This is the recommended way to obtain a mapper for application-wide use when custom configurations are not needed. ### Usage ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; // Reuse the singleton — no allocation cost after first call JsonTemplateMapper mapper = JsonTemplateMapper.defaultInstance(); ``` ``` -------------------------------- ### Custom In-Memory TemplateRepository via Constructor Injection Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Implement a custom TemplateRepository to load templates from an in-memory map. Useful for testing or dynamic template generation. Ensure the template store is thread-safe if accessed concurrently. ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import com.thanhlv.dynamicjsonmapper.TemplateRepository; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; ObjectMapper objectMapper = new ObjectMapper(); // In-memory repository backed by a string map — useful for testing or dynamic templates Map templateStore = new ConcurrentHashMap<>(); templateStore.put("greeting", "{\"hello\": \"${message}\", \"lang\": \"${lang}\"}"); TemplateRepository inMemoryRepo = new TemplateRepository() { @Override public JsonNode getTemplate(String templatePath) { String json = templateStore.get(templatePath); if (json == null) { throw new IllegalArgumentException("Template not found: " + templatePath); } try { return objectMapper.readTree(json); } catch (Exception e) { throw new RuntimeException("Failed to parse template", e); } } // clear() is a no-op default — override if the store supports eviction }; JsonTemplateMapper mapper = new JsonTemplateMapper(objectMapper, inMemoryRepo); JsonNode result = mapper.render("greeting", Map.of( "${message}", "world", "${lang}", "en" )); System.out.println(result.path("hello").asText()); // "world" System.out.println(result.path("lang").asText()); // "en" ``` -------------------------------- ### Linked child templates via $template_ref and $source Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/docs/FEATURES.md Supports linking child templates within a parent template using `$template_ref` for the child template path and `$source` to specify the data source from `rawData`. Validation rules ensure correct usage, and rendering handles null, array, and object sources appropriately. ```APIDOC ## Template Reference Resolution ### Description This feature allows for modular template design by enabling the linking of child templates within a parent template. The `$template_ref` property specifies the path to the child template, and `$source` indicates a placeholder in the `rawData` from which to pull data for the child template. Validation ensures that both properties are present and correctly formatted, and the rendering logic adapts based on whether the `$source` resolves to `null`, an array, or an object. ### Validation Rules - `$template_ref` and `$source` must both be present and textual. - `$source` must be in the format of a placeholder token (e.g., `${items}`). - The value resolved by `$source` must be either a JSON object or an array. Primitive source values will result in an `IllegalArgumentException`. ### Rendering Behavior - If `$source` resolves to `null`, the rendered field will be JSON `null`. - If `$source` resolves to an array, the child template will be rendered once for each item in the array. - For object items within an array, their properties are exposed as placeholders to the child template (e.g., `id` becomes `${id}`). - For primitive items within an array, all child-template placeholders will be filled with that primitive value, unless overridden by parent raw data. ``` -------------------------------- ### Shared default mapper and instance-based API Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/docs/FEATURES.md Provides a singleton instance of `JsonTemplateMapper` via `defaultInstance()` for shared use, as well as the ability to instantiate `JsonTemplateMapper` directly for isolated configurations. Public API methods include `render`, `jsonNodeToString`, and `refreshCache`. ```APIDOC ## JsonTemplateMapper API ### Description The `JsonTemplateMapper` class offers both a shared, globally accessible default instance and the flexibility to create independent instances for specific configurations. This allows for easy access to a common mapper or for scenarios requiring distinct settings. The primary public methods provide core functionality for rendering JSON, converting `JsonNode` to strings, and managing the cache. ### Public API Methods - `render(String templatePath, Map rawData)`: Renders a JSON template. - `jsonNodeToString(JsonNode node)`: Converts a `JsonNode` to a pretty-printed JSON string. - `refreshCache()`: Clears the template repository cache. ### Instance Management - `JsonTemplateMapper.defaultInstance()`: Returns a reusable singleton instance. - Direct instantiation: `new JsonTemplateMapper(...)` allows for custom configurations. ``` -------------------------------- ### Pretty JSON output utility Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/docs/FEATURES.md The `JsonTemplateMapper#jsonNodeToString(...)` method utility formats a `JsonNode` object into a human-readable, pretty-printed JSON string. ```APIDOC ## JsonTemplateMapper#jsonNodeToString(...) ### Description This utility method takes a Jackson `JsonNode` object and converts it into a string representation of JSON. The output is formatted for readability, commonly referred to as 'pretty-printing', which includes indentation and line breaks. ### Method `jsonNodeToString(JsonNode node)` ### Parameters #### Path Parameters - **node** (JsonNode) - Required - The `JsonNode` to convert to a string. ### Response #### Success Response (String) - A pretty-printed JSON string representation of the input `JsonNode`. ``` -------------------------------- ### Cache refresh Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/docs/FEATURES.md The `JsonTemplateMapper#refreshCache()` method allows for clearing the template repository's cache. For repositories that do not implement caching, the `TemplateRepository#clear()` method is optional and defaults to a no-operation. ```APIDOC ## JsonTemplateMapper#refreshCache() ### Description This method provides a mechanism to invalidate and clear the cache used by the `TemplateRepository`. This is useful when templates might have been updated externally and the mapper needs to reload them. For repository implementations that do not inherently cache templates, the `clear()` method on the `TemplateRepository` interface is optional and typically does nothing by default. ### Method `refreshCache()` ### Cache Clearing - Clears the cache of the configured `TemplateRepository`. - `TemplateRepository#clear()` is called if implemented. ``` -------------------------------- ### Serialize JsonNode to Pretty-Printed String Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Use `jsonNodeToString` to convert a rendered `JsonNode` into a human-readable, pretty-printed JSON string. This is useful for debugging, logging, or direct API responses. ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import tools.jackson.databind.JsonNode; import java.util.Map; JsonTemplateMapper mapper = JsonTemplateMapper.defaultInstance(); JsonNode result = mapper.render("templates/user-template.json", Map.of( "${name}", "Linh", "${tuoi}", 30, "${noio}", "Hồ Chí Minh" )); String json = mapper.jsonNodeToString(result); System.out.println(json); // { // "status" : "SUCCESS", // "data" : { // "account_info" : { // "user_name" : "Linh", // "age" : 30 // }, // "location_details" : { // "city" : "Hồ Chí Minh", // "country" : "Việt Nam" // } // }, // "metadata" : { // "server_id" : "SV-01" // } // } ``` -------------------------------- ### In-memory template caching Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/docs/FEATURES.md The `CachingClasspathTemplateRepository` caches parsed templates in a `ConcurrentHashMap` for efficient reuse across multiple render operations. Deep copies of cached templates are used during rendering to prevent mutation of cached entries. ```APIDOC ## CachingClasspathTemplateRepository ### Description This implementation of `TemplateRepository` utilizes an in-memory cache, specifically a `ConcurrentHashMap`, to store parsed JSON templates. This caching mechanism significantly improves performance by avoiding repeated parsing of the same templates. To ensure thread safety and prevent unintended modifications, rendering operations always work on a `deepCopy()` of the cached template, preserving the integrity of the cache. ### Cache Management - Templates are stored as `JsonNode` objects. - `ConcurrentHashMap` is used for thread-safe access. - `deepCopy()` is used during rendering to prevent cache mutation. ``` -------------------------------- ### Extend CachingClasspathTemplateRepository for Custom ClassLoader Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Subclass CachingClasspathTemplateRepository to load templates from a specific classloader, such as one used by a plugin. The built-in caching mechanism is preserved. Remember to call mapper.refreshCache() after hot-reloading templates. ```java import com.thanhlv.dynamicjsonmapper.CachingClasspathTemplateRepository; import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; import tools.jackson.databind.ObjectMapper; import java.io.InputStream; import java.util.Map; ObjectMapper objectMapper = new ObjectMapper(); // Load templates from a different classloader (e.g., a plugin module) CachingClasspathTemplateRepository pluginRepo = new CachingClasspathTemplateRepository(objectMapper) { @Override protected InputStream openTemplateStream(String templatePath) { // Delegate to a specific module's classloader return MyPluginModule.class.getClassLoader().getResourceAsStream(templatePath); } }; JsonTemplateMapper mapper = new JsonTemplateMapper(objectMapper, pluginRepo); var result = mapper.render("templates/plugin-response.json", Map.of( "${status}", "OK", "${payload}", "data from plugin" )); // Evict plugin template cache after a hot reload mapper.refreshCache(); ``` -------------------------------- ### Refresh JsonTemplateMapper Cache Source: https://github.com/thanhlv-com/dynamicjsonmapper/blob/main/README.md Command to clear the in-memory cache used by JsonTemplateMapper. This is useful if template files have been updated and the mapper needs to reload them. ```java mapper.refreshCache(); ``` -------------------------------- ### Clear Template Cache Source: https://context7.com/thanhlv-com/dynamicjsonmapper/llms.txt Call `refreshCache()` to invalidate the in-memory template cache. This forces templates to be reloaded from the classpath on the next `render()` call, useful for development or testing scenarios with updated templates. ```java import com.thanhlv.dynamicjsonmapper.JsonTemplateMapper; JsonTemplateMapper mapper = JsonTemplateMapper.defaultInstance(); // ... render calls load and cache templates ... // Evict all cached templates — next render() call reloads from classpath mapper.refreshCache(); // Render again — template is freshly loaded and re-cached mapper.render("templates/user-template.json", java.util.Map.of( "${name}", "Minh", "${tuoi}", 28, "${noio}", "Đà Nẵng" )); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.