### Initialize and Use CRUDServiceClient Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Demonstrates initializing CRUDServiceClient with basic, custom path/version, and API secret configurations. Includes examples for retrieving all, by ID, by attribute, and storing single/multiple objects. ```java import eu.miaplatform.customplugin.CRUDServiceClient; import eu.miaplatform.customplugin.ServiceClientFactory; import eu.miaplatform.customplugin.CustomPluginHeadersPropagator; import eu.miaplatform.customplugin.HeadersPropagatorFactory; import java.util.stream.Stream; import java.util.Arrays; public class CRUDServiceExample { public static void main(String[] args) { // Create headers propagator for authentication CustomPluginHeadersPropagator headersPropagator = HeadersPropagatorFactory.getCustomPluginHeadersPropagator(); headersPropagator.add("miauserid", "user-123"); headersPropagator.add("miausergroups", "admin"); // Initialize CRUD client with different configurations // Basic client CRUDServiceClient basicClient = ServiceClientFactory.getCRUDServiceClient(headersPropagator); // Client with custom API path and version CRUDServiceClient customClient = ServiceClientFactory.getCRUDServiceClient( "http://crud-service:3000", // apiPath 2, // version headersPropagator ); // Client with API secret for authentication CRUDServiceClient secureClient = ServiceClientFactory.getCRUDServiceClient( "http://crud-service:3000", // apiPath "your-api-secret", // apiSecret 2, // version headersPropagator ); // Retrieve all heroes from collection Stream allHeroes = basicClient.retrieveAll(Hero.class); allHeroes.forEach(hero -> System.out.println("Hero: " + hero.getName() + " (Power: " + hero.getPower() + ")") ); // Retrieve single hero by ID Hero hero = basicClient.retrieveById("507f1f77bcf86cd799439011", Hero.class); if (hero != null) { System.out.println("Found hero: " + hero.getName()); } // Retrieve by specific attribute Stream marvelHeroes = basicClient.retrieveByAttribute("universe", "Marvel", Hero.class); marvelHeroes.forEach(h -> System.out.println("Marvel Hero: " + h.getName())); // Store a single new hero Hero newHero = new Hero("Spider-Man", 85, "Marvel"); String heroId = basicClient.storeSingle(newHero, Hero.class); System.out.println("Created hero with ID: " + heroId); // Store multiple heroes at once Stream heroesToStore = Arrays.asList( new Hero("Batman", 90, "DC"), new Hero("Superman", 100, "DC"), new Hero("Wonder Woman", 95, "DC") ).stream(); Stream createdIds = basicClient.storeMulti(heroesToStore, Hero.class); createdIds.forEach(id -> System.out.println("Created hero ID: " + id)); } } ``` -------------------------------- ### Get Direct Service Proxy Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Obtain a service proxy for direct communication with a specific microservice using its name and initialization options. ```java Service serviceClient = ServiceClientFactory.getDirectServiceProxy("my-microservice", initOptions); ``` -------------------------------- ### Get Service Proxy via Gateway Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Retrieve a service proxy that utilizes the microservice gateway for communication, configured with provided initialization options. ```java Service serviceClient = ServiceClientFactory.getServiceProxy(initOptions); ``` -------------------------------- ### Access Original Request Path Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Get the path of the original incoming request from the PreDecoratorRequest object. ```java preDecoratorRequest.getOriginalRequestPath() ``` -------------------------------- ### Initialize Default InitServiceOptions Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Use this to create a default instance of InitServiceOptions with standard port and protocol settings. ```java InitServiceOptions initOptions = new InitServiceOptions(); ``` -------------------------------- ### Initialize Custom InitServiceOptions with Headers Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Create a custom InitServiceOptions instance using the builder pattern to include specific headers, such as Mia Platform headers. ```java Map customHeaders = ... // headers InitServiceOptions initOptions = InitServiceOptions.builder().headers(customHeaders).build(); ``` -------------------------------- ### Configure Environment Variables with EnvConfiguration Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Manages required environment variables using a singleton pattern. Validates configuration on startup and provides access to environment values. ```java import eu.miaplatform.service.environment.EnvConfiguration; import eu.miaplatform.service.environment.EnvVariable; import eu.miaplatform.service.environment.InvalidEnvConfigurationException; // Required environment variables for Mia-Platform: // USERID_HEADER_KEY, GROUPS_HEADER_KEY, CLIENTTYPE_HEADER_KEY, // BACKOFFICE_HEADER_KEY, MICROSERVICE_GATEWAY_SERVICE_NAME public class Application { public static void main(String[] args) { try { // Parse with default required variables only EnvConfiguration.parseEnvironment(); // Or parse with custom environment schema EnvVariable[] customSchema = new EnvVariable[]{ new EnvVariable("DATABASE_URL", true), // required new EnvVariable("CACHE_TTL", false, "3600"), // optional with default new EnvVariable("LOG_LEVEL", false) // optional, no default }; EnvConfiguration.parseEnvironment(customSchema); // Access environment values String userId = EnvConfiguration.getInstance().get("USERID_HEADER_KEY"); String dbUrl = EnvConfiguration.getInstance().get("DATABASE_URL"); System.out.println("User ID Header: " + userId); System.out.println("Database URL: " + dbUrl); } catch (InvalidEnvConfigurationException e) { System.err.println("Missing required environment variable: " + e.getMessage()); System.exit(1); } } } ``` -------------------------------- ### Configure Service Proxy with InitServiceOptions Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Configures service proxy connections using a builder pattern for port, protocol, headers, and URL prefix settings. ```java import eu.miaplatform.service.InitServiceOptions; import eu.miaplatform.service.Protocol; import java.util.HashMap; import java.util.Map; // Default configuration (port: 3000, protocol: HTTP) InitServiceOptions defaultOptions = new InitServiceOptions(); // Custom configuration with builder pattern Map customHeaders = new HashMap<>(); customHeaders.put("x-request-id", "unique-request-123"); customHeaders.put("x-api-key", "your-api-key"); customHeaders.put("miauserid", "user-456"); customHeaders.put("miausergroups", "admin,users"); InitServiceOptions customOptions = InitServiceOptions.builder() .port(8080) .protocol(Protocol.HTTPS) .headers(customHeaders) .prefix("/api/v1") .build(); System.out.println("Port: " + customOptions.getPort()); System.out.println("Protocol: " + customOptions.getProtocol()); ``` -------------------------------- ### Gateway Service Proxy Usage in Java Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Use getServiceProxy to route requests through the Mia-Platform microservice gateway. Requires the MICROSERVICE_GATEWAY_SERVICE_NAME environment variable to be set. ```java import eu.miaplatform.customplugin.ServiceClientFactory; import eu.miaplatform.service.InitServiceOptions; import eu.miaplatform.service.Service; import eu.miaplatform.service.environment.EnvConfiguration; import okhttp3.Response; import java.io.IOException; public class GatewayServiceExample { public static void main(String[] args) throws Exception { // Ensure environment is configured EnvConfiguration.parseEnvironment(); InitServiceOptions options = InitServiceOptions.builder() .port(3000) .build(); // Get proxy through microservice gateway Service gatewayService = ServiceClientFactory.getServiceProxy(options); if (gatewayService != null) { try { // All requests go through the gateway Response response = gatewayService.get("/api/products", "category=electronics", null); System.out.println("Gateway Response: " + response.code()); System.out.println("Body: " + response.body().string()); } catch (IOException e) { System.err.println("Gateway request failed: " + e.getMessage()); } } else { System.err.println("MICROSERVICE_GATEWAY_SERVICE_NAME not configured"); } } } ``` -------------------------------- ### Implement PRE Decorator Request Handling in Java Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Use PreDecoratorRequest to access request details and DecoratorResponseFactory to return modified requests or abort the chain. ```java import eu.miaplatform.decorators.DecoratorResponse; import eu.miaplatform.decorators.DecoratorResponseFactory; import eu.miaplatform.decorators.predecorators.PreDecoratorRequest; import java.io.Serializable; import java.util.HashMap; import java.util.Map; public class PreDecoratorHandler { public DecoratorResponse handlePreDecorator(PreDecoratorRequest request) { // Access original request information String method = request.getOriginalRequestMethod(); String path = request.getOriginalRequestPath(); Map headers = request.getOriginalRequestHeaders(); Map query = request.getOriginalRequestQuery(); Serializable body = request.getOriginalRequestBody(); // Access user context from Mia-Platform headers String userId = request.getUserId(); String groups = request.getGroups(); String clientType = request.getClientType(); String isBackOffice = request.isFromBackOffice(); System.out.println("Request: " + method + " " + path); System.out.println("User ID: " + userId); System.out.println("Groups: " + groups); // Option 1: Leave request unmodified if (path.startsWith("/public/")) { return DecoratorResponseFactory.makePreDecoratorResponse( request.leaveOriginalRequestUnmodified() ); } // Option 2: Modify the request Map newHeaders = new HashMap<>(headers); newHeaders.put("X-Processed-By", "pre-decorator"); newHeaders.put("X-Request-Time", String.valueOf(System.currentTimeMillis())); Map newQuery = new HashMap<>(query); newQuery.put("decorated", "true"); PreDecoratorRequest modifiedRequest = request.changeOriginalRequest() .setMethod(method) .setPath(path) .setHeaders(newHeaders) .setQuery(newQuery) .setBody(body) .build(); return DecoratorResponseFactory.makePreDecoratorResponse(modifiedRequest); } public DecoratorResponse handleAuthorizationDecorator(PreDecoratorRequest request) { String userId = request.getUserId(); String groups = request.getGroups(); // Check authorization - abort chain if unauthorized if (userId == null || userId.isEmpty()) { Map errorHeaders = new HashMap<>(); errorHeaders.put("Content-Type", "application/json"); Map errorBody = new HashMap<>(); errorBody.put("error", "Unauthorized"); errorBody.put("message", "User authentication required"); return DecoratorResponseFactory.abortChain( 401, (Serializable) errorBody, errorHeaders ); } // Check for admin access on sensitive paths String path = request.getOriginalRequestPath(); if (path.startsWith("/admin/") && !groups.contains("admin")) { Map errorHeaders = new HashMap<>(); errorHeaders.put("Content-Type", "application/json"); Map errorBody = new HashMap<>(); errorBody.put("error", "Forbidden"); errorBody.put("message", "Admin access required"); return DecoratorResponseFactory.abortChain( 403, (Serializable) errorBody, errorHeaders ); } // Authorization passed, continue without modification return DecoratorResponseFactory.makePreDecoratorResponse( request.leaveOriginalRequestUnmodified() ); } } ``` -------------------------------- ### Constructing MongoDB Queries with QueryBuilder Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Demonstrates the use of QueryBuilder to create equality, comparison, array-based, and logical queries. Requires the CRUD service client and appropriate headers propagator. ```java import eu.miaplatform.crud.library.QueryBuilder; import eu.miaplatform.customplugin.CRUDServiceClient; import eu.miaplatform.customplugin.ServiceClientFactory; import eu.miaplatform.customplugin.HeadersPropagatorFactory; import eu.miaplatform.customplugin.CustomPluginHeadersPropagator; import java.util.stream.Stream; public class QueryBuilderExample { public static void main(String[] args) { CustomPluginHeadersPropagator propagator = HeadersPropagatorFactory.getCustomPluginHeadersPropagator(); CRUDServiceClient crudClient = ServiceClientFactory.getCRUDServiceClient(propagator); // Simple equality query QueryBuilder simpleQuery = new QueryBuilder() .equals("universe", "Marvel"); // Generates: {"universe":"Marvel"} Stream marvelHeroes = crudClient.retrieveByQuery(simpleQuery, Hero.class); // Comparison operators QueryBuilder comparisonQuery = new QueryBuilder() .greater("power", 80) // power > 80 .lessOrEquals("power", 100); // power <= 100 // Generates: {"power":{"$gt":80},"power":{"$lte":100}} Stream powerfulHeroes = crudClient.retrieveByQuery(comparisonQuery, Hero.class); // Not equals query QueryBuilder notEqualsQuery = new QueryBuilder() .notEquals("status", "inactive"); // Generates: {"status":{"$ne":"inactive"}} // In array query - find heroes in specific universes QueryBuilder inArrayQuery = new QueryBuilder() .inArray("universe", "Marvel", "DC", "Image"); // Generates: {"universe":{"$in":["Marvel","DC","Image"]}} // Not in array query QueryBuilder notInQuery = new QueryBuilder() .notInArray("status", "deleted", "archived"); // Generates: {"status":{"$nin":["deleted","archived"]}} // AND logical operator - combine multiple conditions QueryBuilder andQuery = new QueryBuilder().and( new QueryBuilder().equals("universe", "Marvel"), new QueryBuilder().greater("power", 70), new QueryBuilder().notEquals("status", "inactive") ); // Generates: {"$and":[{"universe":"Marvel"},{"power":{"$gt":70}},{"status":{"$ne":"inactive"}}]} // OR logical operator QueryBuilder orQuery = new QueryBuilder().or( new QueryBuilder().equals("universe", "Marvel"), new QueryBuilder().equals("universe", "DC") ); // Generates: {"$or":[{"universe":"Marvel"},{"universe":"DC"}]} // NOR logical operator QueryBuilder norQuery = new QueryBuilder().nor( new QueryBuilder().equals("status", "deleted"), new QueryBuilder().equals("status", "archived") ); // Generates: {"$nor":[{"status":"deleted"},{"status":"archived"}]} // Complex nested query QueryBuilder complexQuery = new QueryBuilder().and( new QueryBuilder().or( new QueryBuilder().equals("universe", "Marvel"), new QueryBuilder().equals("universe", "DC") ), new QueryBuilder().greaterOrEquals("power", 50), new QueryBuilder().less("power", 100) ); Stream results = crudClient.retrieveByQuery(complexQuery, Hero.class); results.forEach(hero -> System.out.println(hero.getName() + " (" + hero.getUniverse() + "): " + hero.getPower()) ); // Build query string for debugging String queryString = complexQuery.build(); System.out.println("Generated Query: " + queryString); } } ``` -------------------------------- ### Direct Service Proxy Usage in Java Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Use getDirectServiceProxy to communicate directly with a specific microservice. Requires InitServiceOptions with port and header configuration. ```java import eu.miaplatform.customplugin.ServiceClientFactory; import eu.miaplatform.service.InitServiceOptions; import eu.miaplatform.service.Service; import okhttp3.Response; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class DirectServiceExample { public static void main(String[] args) { // Configure service options with authentication headers Map headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("Authorization", "Bearer token123"); InitServiceOptions options = InitServiceOptions.builder() .port(3000) .headers(headers) .build(); // Get direct proxy to a specific microservice Service userService = ServiceClientFactory.getDirectServiceProxy("user-service", options); try { // GET request with query string Response getResponse = userService.get("/users", "status=active&limit=10", null); System.out.println("GET Status: " + getResponse.code()); System.out.println("GET Body: " + getResponse.body().string()); // POST request with JSON body String newUser = "{\"name\": \"John Doe\", \"email\": \"john@example.com\"}"; Response postResponse = userService.post("/users", newUser, null, null); System.out.println("POST Status: " + postResponse.code()); // PUT request to update resource String updateUser = "{\"name\": \"John Smith\", \"email\": \"john.smith@example.com\"}"; Response putResponse = userService.put("/users/123", updateUser, null, null); System.out.println("PUT Status: " + putResponse.code()); // PATCH request for partial update String patchData = "{\"email\": \"newemail@example.com\"}"; Response patchResponse = userService.patch("/users/123", patchData, null, null); System.out.println("PATCH Status: " + patchResponse.code()); // DELETE request Response deleteResponse = userService.delete("/users/123", "{}", null, null); System.out.println("DELETE Status: " + deleteResponse.code()); } catch (IOException e) { System.err.println("Request failed: " + e.getMessage()); } } } ``` -------------------------------- ### Implement POST Decorator Handlers in Java Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Provides methods to leave responses unmodified, enrich successful responses with metadata, or transform error responses using the DecoratorResponseFactory. ```java import eu.miaplatform.decorators.DecoratorResponse; import eu.miaplatform.decorators.DecoratorResponseFactory; import eu.miaplatform.decorators.postdecorators.PostDecoratorRequest; import java.io.Serializable; import java.util.HashMap; import java.util.Map; public class PostDecoratorHandler { public DecoratorResponse handlePostDecorator(PostDecoratorRequest request) { // Access original request information String method = request.getOriginalRequestMethod(); String path = request.getOriginalRequestPath(); Map requestHeaders = request.getOriginalRequestHeaders(); Map requestQuery = request.getOriginalRequestQuery(); Serializable requestBody = request.getOriginalRequestBody(); // Access original response information int statusCode = request.getOriginalResponseStatusCode(); Map responseHeaders = request.getOriginalResponseHeaders(); Serializable responseBody = request.getOriginalResponseBody(); // Access user context String userId = request.getUserId(); String groups = request.getGroups(); System.out.println("Response for: " + method + " " + path); System.out.println("Status Code: " + statusCode); System.out.println("User: " + userId); // Option 1: Leave response unmodified if (statusCode >= 400) { // Don't modify error responses return DecoratorResponseFactory.makePostDecoratorResponse( request.leaveOriginalResponseUnmodified() ); } // Option 2: Modify the response Map newHeaders = new HashMap<>(responseHeaders); newHeaders.put("X-Processed-By", "post-decorator"); newHeaders.put("X-Response-Time", String.valueOf(System.currentTimeMillis())); PostDecoratorRequest modifiedResponse = request.changeOriginalResponse() .setStatusCode(statusCode) .setHeaders(newHeaders) .setBody(responseBody) .build(); return DecoratorResponseFactory.makePostDecoratorResponse(modifiedResponse); } public DecoratorResponse handleResponseEnrichment(PostDecoratorRequest request) { int statusCode = request.getOriginalResponseStatusCode(); Serializable originalBody = request.getOriginalResponseBody(); // Enrich successful responses with metadata if (statusCode == 200 && originalBody instanceof Map) { @SuppressWarnings("unchecked") Map body = new HashMap<>((Map) originalBody); // Add metadata to response Map metadata = new HashMap<>(); metadata.put("processedAt", System.currentTimeMillis()); metadata.put("processedBy", "enrichment-decorator"); metadata.put("userId", request.getUserId()); body.put("_metadata", metadata); Map headers = new HashMap<>(request.getOriginalResponseHeaders()); headers.put("X-Enriched", "true"); PostDecoratorRequest enrichedResponse = request.changeOriginalResponse() .setStatusCode(200) .setHeaders(headers) .setBody((Serializable) body) .build(); return DecoratorResponseFactory.makePostDecoratorResponse(enrichedResponse); } return DecoratorResponseFactory.makePostDecoratorResponse( request.leaveOriginalResponseUnmodified() ); } public DecoratorResponse handleErrorTransformation(PostDecoratorRequest request) { int statusCode = request.getOriginalResponseStatusCode(); // Transform 500 errors to user-friendly responses if (statusCode >= 500) { Map headers = new HashMap<>(); headers.put("Content-Type", "application/json"); Map friendlyError = new HashMap<>(); friendlyError.put("error", "Service Unavailable"); friendlyError.put("message", "An internal error occurred. Please try again later."); friendlyError.put("code", "INTERNAL_ERROR"); friendlyError.put("timestamp", System.currentTimeMillis()); // Abort chain with transformed error return DecoratorResponseFactory.abortChain( 503, (Serializable) friendlyError, headers ); } return DecoratorResponseFactory.makePostDecoratorResponse( request.leaveOriginalResponseUnmodified() ); } } ``` -------------------------------- ### Define Hero and Author CRUD Models Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Models for 'heroes' and 'authors' collections, extending BaseObject and implementing Serializable. They include fields with SerializedName annotations and constructors. ```java import eu.miaplatform.crud.library.annotations.CollectionAnnotation; import eu.miaplatform.crud.model.BaseObject; import com.google.gson.annotations.SerializedName; import java.io.Serializable; @CollectionAnnotation("heroes") public class Hero extends BaseObject implements Serializable { @SerializedName("name") private String name; @SerializedName("power") private int power; @SerializedName("universe") private String universe; public Hero(String name, int power, String universe) { this.name = name; this.power = power; this.universe = universe; } // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPower() { return power; } public void setPower(int power) { this.power = power; } public String getUniverse() { return universe; } public void setUniverse(String universe) { this.universe = universe; } } @CollectionAnnotation("authors") public class Author extends BaseObject implements Serializable { @SerializedName("firstName") private String firstName; @SerializedName("lastName") private String lastName; @SerializedName("books") private int books; public Author(String firstName, String lastName, int books) { this.firstName = firstName; this.lastName = lastName; this.books = books; } // Getters and setters public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getBooks() { return books; } } ``` -------------------------------- ### Access Original Request Query String Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Obtain the querystring parameters of the original incoming request from the PreDecoratorRequest object. ```java preDecoratorRequest.getOriginalRequestQuery() ``` -------------------------------- ### Creating Decorator Responses Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Static factory method to generate a DecoratorResponse from a modified or unmodified PostDecoratorRequest. ```java DecoratorResponseFactory.makePostDecoratorResponse(PostDecoratorRequest postDecoratorRequest) ``` -------------------------------- ### Create Pre-Decorator Response Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Generate a DecoratorResponse instance from a PreDecoratorRequest, which can be either modified or unmodified. ```java DecoratorResponseFactory.makePreDecoratorResponse(preDecoratorRequest) ``` -------------------------------- ### Access Original Request Method Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Retrieve the HTTP method of the original incoming request using the PreDecoratorRequest instance. ```java preDecoratorRequest.getOriginalRequestMethod() ``` -------------------------------- ### Propagate Custom Headers with Java Source: https://context7.com/mia-platform/custom-plugin-java/llms.txt Use CustomPluginHeadersPropagator to add and manage headers for downstream services. This includes authentication, tracing, and custom application headers. Headers are automatically forwarded when using ServiceClientFactory clients. ```java import eu.miaplatform.customplugin.CustomPluginHeadersPropagator; import eu.miaplatform.customplugin.HeadersPropagatorFactory; import eu.miaplatform.customplugin.CustomPluginHeader; import eu.miaplatform.customplugin.CRUDServiceClient; import eu.miaplatform.customplugin.ServiceClientFactory; import java.util.List; import java.util.Map; import java.util.stream.Stream; public class HeadersPropagationExample { public void processRequest(Map incomingHeaders) { // Create headers propagator CustomPluginHeadersPropagator propagator = HeadersPropagatorFactory.getCustomPluginHeadersPropagator(); // Propagate Mia-Platform authentication headers propagator.add("miauserid", incomingHeaders.get("miauserid")); propagator.add("miausergroups", incomingHeaders.get("miausergroups")); propagator.add("miaclienttype", incomingHeaders.get("miaclienttype")); // Add tracing headers propagator.add("x-request-id", incomingHeaders.get("x-request-id")); propagator.add("x-correlation-id", incomingHeaders.get("x-correlation-id")); // Add custom application headers propagator.add("x-source-service", "my-custom-service"); propagator.add("x-processing-time", String.valueOf(System.currentTimeMillis())); // Retrieve all configured headers List headers = propagator.getHeaders(); System.out.println("Propagating " + headers.size() + " headers:"); for (CustomPluginHeader header : headers) { System.out.println(" " + header.getName() + ": " + header.getValue()); } // Use propagator with CRUD client - headers automatically forwarded CRUDServiceClient crudClient = ServiceClientFactory.getCRUDServiceClient(propagator); // All CRUD operations will include propagated headers Stream heroes = crudClient.retrieveAll(Hero.class); heroes.forEach(hero -> System.out.println("Hero: " + hero.getName())); } } ``` -------------------------------- ### Access Original Request Headers Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Retrieve the headers associated with the original incoming request via the PreDecoratorRequest instance. ```java preDecoratorRequest.getOriginalRequestHeaders() ``` -------------------------------- ### PostDecoratorRequest Interface Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Methods available on the PostDecoratorRequest instance to access original request and response data. ```APIDOC ## PostDecoratorRequest Accessors ### Description Methods to retrieve information about the original request and response. ### Methods - **getOriginalRequestMethod()** (String) - Returns the original request method - **getOriginalRequestPath()** (String) - Returns the path of the original request - **getOriginalRequestHeaders()** (Map) - Returns the headers of the original request - **getOriginalRequestQuery()** (String) - Returns the querystring of the original request - **getOriginalRequestBody()** (Object) - Returns the body of the original request - **getOriginalResponseBody()** (Object) - Returns the body of the original response - **getOriginalResponseHeaders()** (Map) - Returns the headers of the original response - **getOriginalResponseStatusCode()** (int) - Returns the status code of the original response ``` -------------------------------- ### Access Original Request Body Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Retrieve the body of the original incoming request using the PreDecoratorRequest instance. ```java preDecoratorRequest.getOriginalRequestBody() ``` -------------------------------- ### Modify Original Request Query String Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Change the querystring parameters of the original request by using the builder obtained from `changeOriginalRequest`. ```java preDecoratorRequestProxy.setQuery(newQuery) ``` -------------------------------- ### Abort Decorator Chain Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Create a DecoratorResponse to immediately stop the decorator chain, specifying a final status code, body, and headers. ```java DecoratorResponseFactory.abortChain(finalStatusCode, finalBody, finalHeaders) ``` -------------------------------- ### Accessing Request and Response Data Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Utility methods available on the PostDecoratorRequest instance to retrieve original request and response details. ```java getOriginalRequestMethod() getOriginalRequestPath() getOriginalRequestHeaders() getOriginalRequestQuery() getOriginalRequestBody() getOriginalResponseBody() getOriginalResponseHeaders() getOriginalResponseStatusCode() ``` -------------------------------- ### Aborting the Decorator Chain Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Static factory method to terminate the decorator chain with a specific status code, body, and headers. ```java DecoratorResponseFactory.abortChain(int finalStatusCode, Serializable finalBody, Map finalHeaders) ``` -------------------------------- ### Modify Original Request Path Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Set a new path for the original request by using the builder obtained from `changeOriginalRequest`. ```java preDecoratorRequestProxy.setPath(newPath) ``` -------------------------------- ### Modify Original Request Method Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Use the builder returned by `changeOriginalRequest` to set a new HTTP method for the original request. ```java preDecoratorRequestProxy.setMethod(newMethod) ``` -------------------------------- ### Abort Decorator Chain Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Method to stop the execution of the decorator chain and return a custom response. ```APIDOC ## DecoratorResponseFactory.abortChain ### Description Aborts the decorator chain and returns a specific response to the caller. ### Parameters - **finalStatusCode** (int) - The status code to return - **finalBody** (Serializable) - The body to return - **finalHeaders** (Map) - The headers to return ``` -------------------------------- ### Leave Original Request Unmodified Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Call this function to indicate that the original request should not be altered by the decorator. ```java DecoratorResponseFactory.leaveOriginalRequestUnmodified(preDecoratorRequest) ``` -------------------------------- ### Modifying the Response Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Methods to modify the original response using the PostDecoratorRequestProxy builder. ```APIDOC ## PostDecoratorRequestProxy Response Modification ### Description Use `changeOriginalResponse()` to obtain a builder for modifying the response, or `leaveOriginalResponseUnmodified()` to keep it as is. ### Builder Methods - **setHeaders(Map newHeaders)** - Modify the headers of the original response - **setBody(Serializable newBody)** - Change the body of the original response - **setStatusCode(int statusCode)** - Change the status code of the original response ### Response Factory - **DecoratorResponseFactory.makePostDecoratorResponse(PostDecoratorRequest postDecoratorRequest)** - Creates a DecoratorResponse from the modified or unmodified request object. ``` -------------------------------- ### Modify Original Request Body Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Replace the body of the original request with new content using the builder returned by `changeOriginalRequest`. ```java preDecoratorRequestProxy.setBody(newBody) ``` -------------------------------- ### Modify Original Request Headers Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Update the headers of the original request by providing a new map of headers via the builder returned by `changeOriginalRequest`. ```java preDecoratorRequestProxy.setHeaders(newHeaders) ``` -------------------------------- ### Modifying the Original Response Source: https://github.com/mia-platform/custom-plugin-java/blob/master/README.md Methods available via the changeOriginalResponse builder to update the response forwarded to the caller. ```java setHeaders(Map newHeaders) setBody(Serializable newBody) setStatusCode(int statusCode) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.