### Fluxzero Minimal Example: Event Handling Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/quick-ref.md Demonstrates a basic Fluxzero setup with an event, a handler for that event, and publishing the event. It shows how to define a simple message and a handler that reacts to it. ```java record HelloWorld() {} class HelloWorldHandler { @HandleEvent void handle(HelloWorld e) { System.out.println("Hello World!"); } } Fluxzero.publishEvent(new HelloWorld()); ``` -------------------------------- ### Fluxzero Minimal Example Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/quick-ref.md A basic example demonstrating how to publish an event and handle it using annotations in Fluxzero. ```APIDOC ## Minimal Example This example shows a simple event `HelloWorld` and its handler. [//]: # (@formatter:off) ```java record HelloWorld() {} class HelloWorldHandler { @HandleEvent void handle(HelloWorld e) { System.out.println("Hello World!"); } } Fluxzero.publishEvent(new HelloWorld()); [//]: # (@formatter:on) ``` ``` -------------------------------- ### Publish a Fluxzero Event (Basic) Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/basic-example.md Demonstrates how to initialize Fluxzero, register handlers, and publish an event using the DefaultFluxzero builder and LocalClient. ```java public class ExampleMain { public static void main(final String[] args) { var fluxzero = DefaultFluxzero.builder() .build(LocalClient.newInstance()); fluxzero.registerHandlers(new HelloWorldEventHandler()); fluxzero.eventGateway().publish(new HelloWorld()); } } ``` -------------------------------- ### Serving a React App Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/serving-static-files.md Example of configuring @ServeStatic to serve a single-page application, including fallback to index.html for routing. ```APIDOC ## Serving a React App with @ServeStatic ### Description Configures the application to serve static assets for a Single Page Application (SPA) under a specific web path, with a fallback file for handling client-side routing. ### Method Annotation-based configuration. ### Endpoint Files are served under `/app/**`, with a fallback to `index.html` for unknown paths. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java @ServeStatic(value = "/app", resourcePath = "/static", fallbackFile = "index.html") public class WebFrontend { // ... other handler methods if any } ``` ### Response #### Success Response (200) Returns the requested static file (e.g., `index.html`, JS bundles, CSS) or the fallback file if the specific path is not found. #### Response Example (Content of the static file, e.g., HTML for the SPA) ### Notes - Files in `/static` on the classpath (e.g., under `resources/static/`) or `/static` on disk will be served. - File system resources take precedence over classpath resources if duplicates exist. - Use `classpath:` prefix in `resourcePath` for classpath-only resolution, or `file:` for file system-only resolution. ``` -------------------------------- ### Define a Fluxzero Event Class Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/basic-example.md Creates a simple Java record to represent an event that can be published and handled by Fluxzero. ```java public record HelloWorld() { } ``` -------------------------------- ### GET /games Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Example of testing a GET endpoint that retrieves a list of games. It first registers a game using POST and then fetches the list, asserting that one game is returned and the HTTP status is 200. ```APIDOC ## GET /games ### Description Fetches a list of all games. This endpoint is often tested in conjunction with a POST endpoint that creates a game. ### Method GET ### Endpoint /games ### Parameters #### Query Parameters - **term** (String) - Optional - A search term to filter games. ### Request Example (No request body for GET) ### Response #### Success Response (200) - **List** - A list of Game objects. #### Response Example ```json [ { "id": "game123", "name": "Example Game", "genre": "Action" } ] ``` ``` -------------------------------- ### Simulating Preconditions with Given Methods in Fluxzero Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/testing-your-handlers.md Explains how to use `givenCommands` and `givenEvents` to set up preconditions for tests, simulating a starting state before executing the main action. ```java fixture.givenCommands(new CreateUser(userProfile), new ResetPassword(...)) .whenCommand(new UpdatePassword(...)) .expectEvents(UpdatePassword.class); ``` -------------------------------- ### Combine Static and Dynamic Handlers with @ServeStatic Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/serving-static-files.md This example demonstrates how to integrate static file serving with dynamic API endpoints within the same class. It serves static assets from '/app/static/**' while also handling dynamic GET and POST requests under the '/app' path. ```java @Path("/app") @ServeStatic("static") // serves static files from the /static resource directory for web paths /app/static/** public class AppController { @HandleGet("/status") Status getStatus() { return new Status("OK", Instant.now()); } @HandlePost("/submit") SubmissionResult submitForm(FormData data) { return formService.handle(data); } } ``` -------------------------------- ### CreateObjectType Command Example in Kotlin Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/common-mistakes-and-corrections.md An example of a command for creating new ObjectType aggregates, implementing the ObjectTypeCommand interface and using the @Apply pattern. ```kotlin // Command for creating new aggregates data class CreateObjectType( override val objectTypeId: ObjectTypeId, val name: String, val namePlural: String, val initialJsonSchema: JsonNode // ... other properties ) : Request, ObjectTypeCommand { @Apply fun apply(): ObjectType { // Create new ObjectType with initial version return ObjectType(...) } } ``` -------------------------------- ### Publish a Fluxzero Event (Spring Boot) Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/basic-example.md Shows how to publish a Fluxzero event within a Spring Boot application. Assumes Fluxzero beans are configured, potentially via FluxzeroSpringConfig. ```java @SpringBootApplication public class ExampleMain { public static void main(String... args) { SpringApplication.run(ExampleMain.class, args); Fluxzero.publishEvent(new HelloWorld()); } } ``` -------------------------------- ### Maven Installation: Core Dependencies Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Lists the necessary Fluxzero Java SDK dependencies for Maven projects, including the client, test utilities, and optional test server/proxy modules. ```xml io.fluxzero java-client io.fluxzero java-client tests test io.fluxzero test-server test io.fluxzero proxy test ``` -------------------------------- ### Maven Installation: Fluxzero BOM Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Instructs Maven users to import the Fluxzero BOM for centralized version management, simplifying dependency updates across the project. ```xml io.fluxzero fluxzero-bom ${fluxzero.version} pom import ``` -------------------------------- ### Integrate Fluxzero Client with FluxzeroBuilder Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Builds a Fluxzero application instance, optionally installing it as a global singleton. This is a common step after configuring the client. ```java Fluxzero flux = Fluxzero.builder() .makeApplicationInstance(true) .build(webSocketClient); ``` -------------------------------- ### Publishing Metrics in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/dispatching-messages.md Shows how to publish custom metrics to the Fluxzero Runtime using the SDK. Provides an example of publishing a SystemLoadMetric. ```java Fluxzero.publishMetrics( new SystemLoadMetric(cpu, memory)); ``` -------------------------------- ### Serving a Single-Page Application with @ServeStatic Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Shows an example of serving a React or similar single-page application using @ServeStatic, including setting a fallback file for handling routing within the SPA. ```java @ServeStatic(value = "/app", resourcePath = "/static", fallbackFile = "index.html") public class WebFrontend { ... } ``` -------------------------------- ### Integrate WebSocketClient with FluxzeroBuilder Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/websocketclient-connect-to-the-flux-platform.md Illustrates passing a configured WebSocketClient into the Fluxzero.builder to create and optionally install the Fluxzero instance as a global singleton. ```java Fluxzero fluxzero = Fluxzero.builder() .makeApplicationInstance(true) .build(webSocketClient); ``` -------------------------------- ### Handling GET Requests Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/handling-web-requests.md Handles incoming GET requests to a specific path and returns a list of users. ```APIDOC ## GET /users ### Description Handles incoming GET requests to the '/users' path and returns a list of user accounts. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **UserAccount** (List) - A list of user accounts. #### Response Example ```json [ { "id": "123e4567-e89b-12d3-a456-426614174000", "username": "john_doe" } ] ``` ``` -------------------------------- ### Handle User Creation Event and Dispatch Welcome Email Command (Java) Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/message-handling.md An example of an event handler that triggers when a user is created. It then dispatches a command to send a welcome email using the static Fluxzero.sendCommand method. ```java class UserEventHandler { @HandleEvent void handle(CreateUser event) { Fluxzero.sendCommand( new SendWelcomeEmail(event.getUserProfile())); } } ``` -------------------------------- ### Handle GET requests to /users with @HandleGet Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/handling-web-requests.md This snippet demonstrates how to handle GET requests to a specific path '/users' using the @HandleGet annotation. It returns a list of UserAccount objects, which are then published as a WebResponse. No external dependencies are required beyond standard Java and the Fluxzero SDK. ```java @HandleGet("/users") public List listUsers() { return userService.getAllUsers(); } ``` -------------------------------- ### Handle multiple HTTP methods or custom methods with @HandleWeb Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/handling-web-requests.md This example shows how to use the general @HandleWeb annotation to match multiple HTTP methods (GET, DELETE) for a given path '/users/{userId}'. It also demonstrates how to extract path parameters using @PathParam and conditionally handle requests based on the HTTP method. The handler returns a CompletableFuture to handle asynchronous operations. ```java @HandleWeb(value = "/users/{userId}", method = {"GET", "DELETE"}) public CompletableFuture handleUserRequest(WebRequest request, @PathParam String userId) { return switch (request.getMethod()) { case "GET" -> Fluxzero.query(new GetUser(userId)); case "DELETE" -> Fluxzero.sendCommand(new DeleteUser(userId)); default -> throw new UnsupportedOperationException(); }; } ``` -------------------------------- ### Testing Workflows with Multiple Handlers Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Shows how to test complete workflows involving multiple handlers. This example initializes the `TestFixture` with both `UserCommandHandler` and `UserEventHandler` to simulate a sequence of operations. ```java TestFixture fixture = TestFixture.create(new UserCommandHandler(), new UserEventHandler()); @Test void creatingUserTriggersEmail() { fixture.whenCommand(new CreateUser(userProfile)) .expectCommands(new SendWelcomeEmail(userProfile)); } ``` -------------------------------- ### Use LocalClient for Testing Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/websocketclient-connect-to-the-flux-platform.md Provides an example of using the in-memory LocalClient with Fluxzero.builder for testing or lightweight local development scenarios. ```java Fluxzero fluxzero = Fluxzero.builder().build(new LocalClient()); ``` -------------------------------- ### Advanced @ServeStatic Annotation Configuration Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/serving-static-files.md This example shows a more comprehensive configuration of the @ServeStatic annotation, including setting a fallback file for single-page applications, defining immutable file extensions for aggressive caching, and specifying the cache duration in seconds. ```java @ServeStatic( value = "/assets", resourcePath = "/public", fallbackFile = "index.html", immutableCandidateExtensions = {"js", "css", "svg"}, maxAgeSeconds = 86400 ) ``` -------------------------------- ### Test GET /games Handler Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/testing-web-endpoint-behavior.md Tests fetching a list of games via a GET request to /games. It first preconditions a game registration using POST /games, then asserts that the result contains one game and the web response status is 200. ```java @Test void getGames() { testFixture .givenPost("/games", "/game/game-details.json") // Precondition: register a game .whenGet("/games") // Perform GET request .>expectResult(r -> r.size() == 1) // Assert one game is returned .expectWebResponse(r -> r.getStatus() == 200); // Assert the status of the response } ``` -------------------------------- ### GET /games Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/testing-web-endpoint-behavior.md Fetches a list of all games and asserts the number of games returned and the HTTP status code. ```APIDOC ## GET /games ### Description Fetches a list of all games and asserts the number of games returned and the HTTP status code. ### Method GET ### Endpoint /games ### Parameters #### Path Parameters None #### Query Parameters - **term** (string) - Optional - A search term to filter games. #### Request Body None ### Request Example ```java testFixture .givenPost("/games", "/game/game-details.json") // Precondition: register a game .whenGet("/games") // Perform GET request .>expectResult(r -> r.size() == 1) // Assert one game is returned .expectWebResponse(r -> r.getStatus() == 200); // Assert the status of the response ``` ### Response #### Success Response (200) - **List** (list of objects) - A list of game objects. #### Response Example ```json [ { "title": "Legend of the Skylands", "description": "An epic singleplayer adventure with puzzles and secrets.", "releaseDate": "2025-11-12T00:00:00Z", "tags": [ "adventure", "puzzle", "singleplayer" ] } ] ``` ### Associated Handler ```java @HandleGet @Path("/games") CompletableFuture> getGames(@QueryParam String term) { return Fluxzero.query(new FindGames(term)); } ``` ``` -------------------------------- ### BatchInterceptor Implementation in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/interceptors-dispatching-handling-and-batching.md A sample BatchInterceptor that logs the start of processing for a message batch. It wraps the consumer logic. ```java public class LoggingBatchInterceptor implements BatchInterceptor { @Override public Consumer intercept(Consumer consumer, Tracker tracker) { return batch -> { log.info("Start processing {} messages", batch.size()); consumer.accept(batch); }; } } ``` -------------------------------- ### Dispatching Various Message Types in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/dispatching-messages.md Demonstrates sending different message types asynchronously or synchronously using static methods on the Fluxzero class. Includes examples for commands, queries, events, and schedules with optional metadata. ```java Fluxzero.sendCommand(new CreateUser("Alice")); // Asynchronously send a command Fluxzero.queryAndWait(new GetUserById("user-123")); // Query and block for response Fluxzero.publishEvent(new UserSignUp(...)); // Fire-and-forget event Fluxzero.schedule(new RetryPayment(...), Duration.ofMinutes(5)); // Delayed message ``` ```java Fluxzero.sendCommand(new CreateUser("Bob"), Metadata.of("source","admin-ui")); ``` -------------------------------- ### POST Web Endpoint Handler Example (Java) Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Defines a handler for POST requests to '/games' that accepts GameDetails, sends a RegisterGame command, and returns a GameId. It utilizes Fluxzero's command sending mechanism. ```java import io.fluxzero.sdk.Fluxzero; import io.fluxzero.sdk.annotations.HandlePost; import java.util.concurrent.CompletableFuture; public class GameHandler { @HandlePost("/games") CompletableFuture addGame(GameDetails details) { return Fluxzero.sendCommand(new RegisterGame(details)); } } // Placeholder classes, assuming they are defined elsewhere class GameDetails { // ... fields for title, description, etc. ... } class RegisterGame { public RegisterGame(GameDetails details) {} } class GameId {} ``` -------------------------------- ### JSON Payload for Game Details Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Example JSON file containing details for a game, used as a payload for testing POST web endpoint behavior. ```json { "title": "Legend of the Skylands", "description": "An epic singleplayer adventure with puzzles and secrets.", "releaseDate": "2025-11-12T00:00:00Z", "tags": [ "adventure", "puzzle", "singleplayer" ] } ``` -------------------------------- ### Handle Command with Injected Timestamp Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Example of a handler method that receives an Instant object, automatically injected by a custom parameter resolver. ```java @HandleCommand void handle(CreateOrder command, Instant timestamp) { log.info("Command received at {}", timestamp); } ``` -------------------------------- ### Annotate Event Handler for Spring Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/basic-example.md Marks a Fluxzero event handler as a Spring component, allowing it to be managed by the Spring application context. ```java @Component public class HelloWorldEventHandler { @HandleEvent void handle(HelloWorld event) { System.out.println("Hello World!"); } } ``` -------------------------------- ### Scheduling Messages and Periodic Tasks in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/dispatching-messages.md Demonstrates how to schedule messages for later delivery or to set up periodic tasks using the Fluxzero SDK. Includes examples for delayed message handling and recurring task execution. ```java // Schedule a message to be handled in 5 minutes using @HandleSchedule Fluxzero.schedule(new ReminderFired(), Duration.ofMinutes(5)); // Fire a periodic schedule every hour Fluxzero.schedulePeriodic(new PollExternalApi()); ``` -------------------------------- ### Get Single Project Query Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/code-samples.md Retrieves a single project by its ID. Filters by owner ID unless the user is an admin. ```APIDOC ## GET /projects/{projectId} ### Description Retrieves a single project by its unique identifier, optionally filtered by the owner's ID. ### Method GET ### Endpoint /projects/{projectId} ### Parameters #### Path Parameters - **projectId** (ProjectId) - Required - The unique identifier of the project to retrieve. ### Request Body None ### Response #### Success Response (200) - **Project** - The requested Project object. #### Response Example ```json { "projectId": "proj_123", "name": "Project Alpha", "description": "This is the first project." } ``` ``` -------------------------------- ### Simulating User-Specific Commands in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/testing-your-handlers.md This example shows how to simulate commands executed by a specific user, asserting potential unauthorized access. It supports passing a User object or a user ID string. ```java var user = new MyUser("pete"); fixture.whenCommandByUser(user, "confirm-user.json") .expectExceptionalResult(UnauthorizedException.class); ``` ```java fixture .givenCommands("create-user-pete.json") .whenCommandByUser("pete", "confirm-user.json") .expectExceptionalResult(UnauthorizedException.class); ``` -------------------------------- ### Create a Fluxzero Event Handler Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/basic-example.md Implements a Java class to handle a specific event type using the @HandleEvent annotation. This handler will be registered with Fluxzero to process incoming events. ```java public class HelloWorldEventHandler { @HandleEvent void handle(HelloWorld event) { System.out.println("Hello World!"); } } ``` -------------------------------- ### Publish Custom Metrics using Fluxzero Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Illustrates how to manually publish metrics using the `Fluxzero.publishMetrics(...)` method. It also shows a more advanced example of publishing metrics with additional metadata and delivery guarantees. ```java Fluxzero.publishMetrics(new SystemMetrics("slowProjection", "thresholdExceeded")); ``` ```java Fluxzero.get() .metricsGateway() .publish(new MyMetric("foo"), Metadata.of("critical","true"), Guarantee.STORED); ``` -------------------------------- ### Schedule Command Execution with Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/scheduling.md Demonstrates scheduling a command for future execution, specifically for terminating an account. It also includes the logic to cancel the schedule if the account is reopened. This example utilizes the `Fluxzero.scheduleCommand` method. ```java class UserLifecycleHandler { @HandleEvent void handle(AccountClosed event) { Fluxzero.scheduleCommand( new TerminateAccount( event.getUserId()), "AccountClosed-" + event.getUserId(), Duration.ofDays(30)); } @HandleEvent void handle(AccountReopened event) { Fluxzero.cancelSchedule("AccountClosed-" + event.getUserId()); } } ``` -------------------------------- ### Common Filtering Constraints Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/document-indexing-and-search.md Lists and provides examples of common filtering constraints supported by Fluxzero, including look-ahead, full-text search, field matching, temporal filters, and logical operations. ```APIDOC ## Common Filtering Constraints Fluxzero supports a rich set of constraints: - `lookAhead("cat", paths...)` – search-as-you-type lookups - `query("*text & (cat* | hat)", paths...)` – full-text search - `match(value, path)` – field match - `matchFacet(name, value)` – match field with `@Facet` - `between(min, max, path)` – numeric or time ranges - `since(...)`, `before(...)`, `inLast(...)` – temporal filters - `anyExist(...)` – match if *any* of the fields are present - Logical operations: `not(...)`, `all(...)`, `any(...)` Example: [//]: # (@formatter:off) ```java Fluxzero.search("payments") .match("FAILED", "status") .inLast(Duration.ofDays(1)) .fetchAll(); ``` [//]: # (@formatter:on) ``` -------------------------------- ### Compose URI paths using @Path annotation Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/handling-web-requests.md This example demonstrates how to compose URI paths using the @Path annotation at the package and class levels. Paths are chained from outermost to innermost. A path segment starting with '/' resets the chain. It handles GET requests to '/api/users/{id}'. ```java @Path package my.example.api; @Path("users") public class UserHandler { @Path("{id}") @HandleGet public User getUser(@PathParam String id) { ...} } ``` -------------------------------- ### Gradle Kotlin DSL Dependencies for Fluxzero SDK Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/installation.md This code snippet demonstrates how to configure dependencies for the Fluxzero SDK using Gradle's Kotlin DSL. It utilizes platform BOM support to manage versions and includes the Java client, test client, test server, and proxy modules. ```kotlin dependencies { implementation(platform("io.fluxzero:fluxzero-bom:${fluxzeroVersion}")) implementation("io.fluxzero:java-client") testImplementation("io.fluxzero:java-client", classifier = "tests") testImplementation("io.fluxzero:test-server") testImplementation("io.fluxzero:proxy") } ``` -------------------------------- ### Maven Dependencies for Fluxzero SDK Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/installation.md This snippet shows how to declare the Fluxzero BOM in the dependencyManagement section of a Maven project for centralized version control. It then lists the core Fluxzero Java client, test dependencies, test server, and proxy modules. ```xml io.fluxzero fluxzero-bom ${fluxzero.version} pom import io.fluxzero java-client io.fluxzero java-client tests test io.fluxzero test-server test io.fluxzero proxy test ``` -------------------------------- ### Integrate Test Fixtures with Spring Boot in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Shows how to inject and use `TestFixture` directly within a Spring Boot application for testing. It highlights that no manual setup is needed for Spring Boot applications. ```java @SpringBootTest class AsyncAppTest { @Autowired TestFixture fixture; @Test void testSomething() { fixture.whenCommand("commands/my-command.json") .expectEvents("events/expected-event.json"); } } ``` -------------------------------- ### Making Web Requests in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/dispatching-messages.md Illustrates how to send outbound HTTP requests using the Fluxzero SDK's web request gateway. Shows building a GET request and sending it to a specified URL, waiting for the response. ```java WebRequest request = WebRequest .get("https://api.example.com/data").build(); WebResponse response = Fluxzero.get() .webRequestGateway().sendAndWait(request); ``` -------------------------------- ### Querying Indexed Documents Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/document-indexing-and-search.md Shows how to use the fluent `search(...)` API to query indexed documents by collection name or class, with examples of matching fields, temporal constraints, sorting, and fetching results. ```APIDOC ## Querying Indexed Documents Use the fluent `search(...)` API: ```java List admins = Fluxzero .search("users") .match("admin", "profile/role") .inLast(Duration.ofDays(30)) .sortBy("profile/lastLogin", true) .fetch(100); ``` You can also query by class: ```java List users = Fluxzero .search(UserAccount.class) .match("Netherlands", "profile.country") .fetchAll(); ``` > **Note:** You can choose to split path segments using either a dot (`.`) or a slash (`/`). > For example, `profile.name` and `profile/name` are treated identically. > This flexibility can be useful when working with tools or serializers that prefer one style over the other. ``` -------------------------------- ### Fluxzero Project Layout Conventions Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/quick-ref.md Guidelines for structuring new Fluxzero applications, including package naming, placement of API components, domain models, endpoints, and tests. ```APIDOC ## Standard Fluxzero Project Layout Follow this structure for all new Fluxzero applications: - **Root Package:** `com.example..` ### API Components - Place commands, queries, ID classes, and base command interfaces (e.g., `HomeUpdate`) in `....api`. - Keep the `api` package flat; do not use subpackages for commands/queries/IDs. - Use imperative present-tense for commands (e.g., `AddLight`). - Use `Request` for queries. - Do not create separate event classes. ### Domain Model - Place aggregate roots (e.g., `Home`), entities (e.g., `Light`, `Thermostat`), and value objects (e.g., `HomeDetails`) in `....api.model`. - Enums (e.g., `DeviceType`) and polymorphic interfaces (e.g., `Device`) should also be in the `model` package. ### Endpoints - Place REST endpoints (e.g., `HomeEndpoint`) directly in the root `...` package. - Use `@HandlePost` and `@HandleGet` to expose commands and queries via HTTP. ### Test Structure - Mirror the production layout under `src/test/java`. - Group tests by domain (e.g., `HomeTest`). ### Summary Table | Purpose | Location | |------------------------------|--------------------------------------------| | Root | `com.example..` | | Commands / Queries / IDs | `....api` | | Aggregate / Entities / Enums | `....api.model` | | Base handler interface | `....api` (e.g., `HomeUpdate`) | | REST endpoint(s) | `....HomeEndpoint` | | Tests | `src/test/java/com.example..` | ``` -------------------------------- ### POST /error Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Demonstrates testing an endpoint that is expected to return an error. This example simulates a POST request to '/error', asserts that an IllegalCommandException is thrown, and verifies a 403 Forbidden HTTP status code. ```APIDOC ## POST /error ### Description An example endpoint designed to return an error. It throws an `IllegalCommandException` to simulate an error scenario, resulting in a 403 Forbidden response. ### Method POST ### Endpoint /error ### Parameters #### Request Body - **body** (String) - The request body content. ### Request Example ```json "Simulated error request body" ``` ### Response #### Error Response (403) - **IllegalCommandException** - Indicates a forbidden operation. #### Response Example ```json { "error": "error: Simulated error request body" } ``` ``` -------------------------------- ### Handling Multiple Methods or Paths with @HandleWeb Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/handling-web-requests.md Demonstrates how to use @HandleWeb to match multiple HTTP methods (GET, DELETE) for a given path, including dynamic path parameters. ```APIDOC ## Handle User Request by ID ### Description Handles GET or DELETE requests to '/users/{userId}', extracting the userId from the path. ### Method GET, DELETE ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (String) - Required - The unique identifier of the user. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **UserAccount** (Object) - The user account information for GET requests. - **Void** (String) - Indicates success for DELETE requests. #### Response Example (GET) ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "username": "john_doe" } ``` #### Response Example (DELETE) ```json "User deleted successfully" ``` ``` -------------------------------- ### Initialize FluxzeroBuilder Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/configuring-flux-capacitor.md Demonstrates the basic initialization of the FluxzeroBuilder, which is the primary entry point for configuring a Fluxzero instance. ```java FluxzeroBuilder builder = DefaultFluxzero.builder(); ``` -------------------------------- ### Default Parameter Resolution Example Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/parameter-injection-with-custom-resolvers.md Demonstrates default parameter injection in a Fluxzero handler method. It shows how to receive a CreateUser event, Metadata, and SerializedMessage, logging the message timestamp. ```java import io.fluxzero.sdk.core.annotations.HandleEvent; import io.fluxzero.sdk.core.message.Metadata; import io.fluxzero.sdk.core.message.SerializedMessage; import java.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExampleHandler { private static final Logger log = LoggerFactory.getLogger(ExampleHandler.class); @HandleEvent void handle(CreateUser event, Metadata metadata, SerializedMessage message) { log.info("User created at {}", Instant.ofEpochMilli(message.getTimestamp())); } } ``` -------------------------------- ### Test Fluxzero Handler with TestFixture Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/basic-example.md Utilizes Fluxzero's TestFixture to unit test an event handler in memory. It simulates event handling and allows for basic outcome verification. ```java class HelloWorldEventHandlerTest { @Test void testHelloWorldHandler() { TestFixture.create(new HelloWorldEventHandler()) .whenEvent(new HelloWorld()) .expectThat(fc -> System.out.println( "Event handled successfully!")); } } ``` -------------------------------- ### Using Test Fixtures in Spring Boot Tests (Java) Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/testing-your-handlers.md This example shows how to inject and use a `TestFixture` directly within a Spring Boot test class, leveraging auto-configuration. ```java @SpringBootTest class AsyncAppTest { @Autowired TestFixture fixture; @Test void testSomething() { fixture.whenCommand("commands/my-command.json") .expectEvents("events/expected-event.json"); } } ``` -------------------------------- ### Gradle Groovy DSL Dependencies for Fluxzero SDK Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/installation.md This code snippet shows how to add Fluxzero SDK dependencies to a Gradle project using the Groovy DSL. It leverages platform BOM support for version alignment and includes the necessary artifacts for the Java client and testing. ```groovy dependencies { implementation platform("io.fluxzero:fluxzero-bom:${fluxzeroVersion}") implementation 'io.fluxzero:java-client' testImplementation('io.fluxzero:java-client') { classifier = 'tests' } testImplementation 'io.fluxzero:test-server' testImplementation 'io.fluxzero:proxy' } ``` -------------------------------- ### UpdateObjectType Command Example in Kotlin Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/common-mistakes-and-corrections.md An example of a command to update existing ObjectType aggregates, implementing the ObjectTypeCommand interface and using the @Apply pattern. ```kotlin // Command that operates on existing aggregates data class UpdateObjectType( override val objectTypeId: ObjectTypeId, val name: String? = null, val namePlural: String? = null // ... other properties ) : Request, ObjectTypeCommand { @Apply fun apply(objectType: ObjectType): ObjectType { return objectType.copy( name = name ?: objectType.name, namePlural = namePlural ?: objectType.namePlural // ... other updates ) } } ``` -------------------------------- ### Get Application Properties in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/configuring-application-properties.md Demonstrates retrieving string, boolean, and integer properties using the ApplicationProperties utility. Default values are provided for cases where properties are not found. ```java String name = ApplicationProperties.getProperty("app.name", "DefaultApp"); boolean enabled = ApplicationProperties.getBooleanProperty("feature.toggle", true); int maxItems = ApplicationProperties.getIntegerProperty("limit.items", 100); ``` -------------------------------- ### Dispatching Various Message Types Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Provides examples of dispatching different message types (commands, queries, events, schedules) using static methods on the `Fluxzero` class. It demonstrates asynchronous sending, blocking for responses, and scheduling delayed messages. ```java import io.fluxzero.sdk.java.Fluxzero; import io.fluxzero.sdk.java.example.CreateUser; import io.fluxzero.sdk.java.example.GetUserById; import io.fluxzero.sdk.java.example.UserSignUp; import io.fluxzero.sdk.java.example.RetryPayment; import java.time.Duration; import java.util.concurrent.CompletableFuture; public class MessageDispatcher { public void dispatchMessages() { // Asynchronously send a command Fluxzero.sendCommand(new CreateUser("Alice")); // Query and block for response // Assuming GetUserById returns a UserId or similar response type // UserId id = Fluxzero.queryAndWait(new GetUserById("user-123")); // Fire-and-forget event // Fluxzero.publishEvent(new UserSignUp(...)); // Delayed message Fluxzero.schedule(new RetryPayment(...), Duration.ofMinutes(5)); } public void dispatchWithMetadata() { // Sending a command with optional metadata Fluxzero.sendCommand(new CreateUser("Bob"), Metadata.of("source", "admin-ui")); } public void sendAndForgetCommand() { // Send and forget a command Fluxzero.sendAndForgetCommand(new CreateUser("Alice")); } public void sendCommandAsyncOrBlocking() { // Send and wait (async) for a command response CompletableFuture future = Fluxzero.sendCommand(new CreateUser("Bob")); // Send and wait (blocking) for a command response // Assuming CreateUser returns a UserId or similar response type // UserId id = Fluxzero.sendCommandAndWait(new CreateUser("Charlie")); } // Dummy classes for compilation, replace with actual Fluxzero types static class UserId {} static class Metadata { public static Metadata of(String key, String value) { return new Metadata(); } } static class CreateUser { public CreateUser(String name) {} } static class GetUserById { public GetUserById(String id) {} } static class UserSignUp {} static class RetryPayment {} } ``` -------------------------------- ### Building the Fluxzero Instance Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Demonstrates how to construct a Fluxzero instance using a client and optionally set it as the application-wide global instance. ```APIDOC ## Build Fluxzero Instance ### Description Constructs a `Fluxzero` instance by building it with a provided `Client`. It also shows how to configure it as the global application instance. ### Method Builder pattern ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Build Fluxzero with a client Fluxzero flux = builder.build(myClient); // Build and set as application instance builder.makeApplicationInstance(true).build(myClient); ``` ### Response #### Success Response (200) N/A (This is a code example, not an API call) #### Response Example N/A ``` -------------------------------- ### Handler for GET /games Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/testing-web-endpoint-behavior.md The handler for the GET /games endpoint. It queries for games based on an optional term parameter and returns a list of games. ```java @HandleGet @Path("/games") CompletableFuture> getGames(@QueryParam String term) { return Fluxzero.query(new FindGames(term)); } ``` -------------------------------- ### Create Project Endpoint Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/code-samples.md Creates a new project with the provided details. ```APIDOC ## POST /projects ### Description Creates a new project. ### Method POST ### Endpoint /projects ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **details** (ProjectDetails) - Required - The details of the project to create. ### Request Example ```json { "name": "New Project", "description": "Details about the new project." } ``` ### Response #### Success Response (200) - **ProjectId** - The unique identifier of the newly created project. #### Response Example ```json "proj_789" ``` ``` -------------------------------- ### HandleGet Annotation for HTTP GET Requests in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/annotations.md Handles incoming HTTP GET requests for specified paths. This annotation is a specialization of the more general HandleWeb annotation. ```Java package io.fluxzero.sdk.web; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @HandleWeb(method = HttpMethod.GET) public @interface HandleGet { String[] value() default {}; } ``` -------------------------------- ### Executing Queries (Async, Blocking) in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/dispatching-messages.md Provides examples for executing queries to retrieve data using the Fluxzero SDK. Demonstrates asynchronous query execution returning a CompletableFuture and blocking query execution for immediate results. ```java CompletableFuture result = Fluxzero.query(new GetUserProfile("user123")); ``` ```java UserProfile profile = Fluxzero.queryAndWait(new GetUserProfile("user456")); ``` -------------------------------- ### Fluxzero Routing and Consistency Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/quick-ref.md Details on how Fluxzero ensures message order and consistency using routing keys, and the requirement for command parameter names to match entity fields for automatic routing. ```APIDOC ## Routing & Consistency Fluxzero uses routing keys to ensure that messages with the same key are processed on the same segment, thereby preserving order. ```java public record ShipOrder(@RoutingKey OrderId orderId) { } ``` **Requirement:** Command parameter names must match the `@EntityId` field in entities for automatic routing and binding. ``` -------------------------------- ### Authentication and Authorization Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/code-samples.md Enforces roles and permissions on commands. For example, an admin-only create-user command. ```APIDOC ## Authentication & Authorization ### Description Enforces roles and permissions directly on command interfaces or implementations using annotations like `@RequiresRole`. ### Example An admin-only create-user command signature: ```java @RequiresRole(Role.admin) public record CreateUser(UserId userId, @Valid UserDetails details, Role role) implements UserUpdate ``` This indicates that only users with the 'admin' role can execute the `CreateUser` command. ``` -------------------------------- ### MappingBatchInterceptor for Filtering in Java Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/interceptors-dispatching-handling-and-batching.md An example of a MappingBatchInterceptor that filters messages from a batch, excluding those marked with 'testOnly' metadata. ```java MappingBatchInterceptor filterTestMessages = (batch, tracker) -> { var filtered = batch.getMessages().stream() .filter(m -> !m.getMetadata().containsKey("testOnly")) .toList(); return batch.withMessages(filtered); }; ``` -------------------------------- ### Web Framework Annotations Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/annotations.md Annotations for building web applications and handling HTTP requests within the Fluxzero SDK. ```APIDOC ## Web Framework Annotations ### Description Annotations used for defining web request handlers, parameter binding, and static file serving. - **`io.fluxzero.sdk.web.WebParam`** - Description: A meta-annotation for parameter annotations. Used to inject values from HTTP requests based on the specified `WebParameterSource`. - **`io.fluxzero.sdk.web.ServeStatic`** - Description: Declares a static file handler. Serves files from a resource or file system location at specified web paths. - **`io.fluxzero.sdk.web.QueryParam`** - Description: Injects an HTTP query parameter into a handler method parameter. - **`io.fluxzero.sdk.web.PathParam`** - Description: Injects a path variable from the URI into a handler method parameter. - **`io.fluxzero.sdk.web.Path`** - Description: Declares a path prefix that contributes to the final URI of a web handler. Supports hierarchical path composition. - **`io.fluxzero.sdk.web.HeaderParam`** - Description: Injects an HTTP request header into a handler method parameter. - **`io.fluxzero.sdk.web.FormParam`** - Description: Injects form data parameters from HTTP requests into handler method parameters. - **`io.fluxzero.sdk.web.CookieParam`** - Description: Injects HTTP cookie values into handler method parameters. - **`io.fluxzero.sdk.web.HandleWebResponse`** - Description: Marks a method as a handler for `WebResponse` messages. Typically used to inspect response messages from web request handlers. - **`io.fluxzero.sdk.web.HandleWeb`** - Description: Marks a method as a handler for incoming web requests. Supports configurable path patterns, HTTP methods, and response publishing behavior. - **`io.fluxzero.sdk.web.HandleGet`** - Description: Handles incoming HTTP GET requests for specified paths. This is a specialization of `HandleWeb`. - **`io.fluxzero.sdk.web.HandlePost`** - Description: Handles incoming HTTP POST requests for specified paths. This is a specialization of `HandleWeb`. ``` -------------------------------- ### Handle Event with Default Parameters Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/README.md Example of a handler method that automatically receives the event payload, metadata, and the serialized message. ```java @HandleEvent void handle(CreateUser event, Metadata metadata, SerializedMessage message) { log.info("User created at {}", Instant.ofEpochMilli(message.getTimestamp())); } ``` -------------------------------- ### Create and Configure WebSocketClient Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/guides/websocketclient-connect-to-the-flux-platform.md Instantiates a WebSocketClient with basic configuration, including the service base URL and a name for the service. This client is then used to build the main Fluxzero application instance. ```java WebSocketClient client = WebSocketClient.newInstance( WebSocketClient.ClientConfig.builder() .serviceBaseUrl("wss://my.fluxzero.host") .name("my-service") .build()); Fluxzero fluxzero = Fluxzero.builder().build(client); ``` -------------------------------- ### List Projects Query Source: https://github.com/fluxzero-io/fluxzero-sdk-java/blob/main/docs/code-samples.md Retrieves a list of projects. Filters by owner ID unless the user is an admin. Fetches up to 100 projects. ```APIDOC ## GET /projects ### Description Retrieves a list of projects, optionally filtered by the owner's ID. ### Method GET ### Endpoint /projects ### Query Parameters None ### Request Body None ### Response #### Success Response (200) - **List** - A list of Project objects. #### Response Example ```json [ { "projectId": "proj_123", "name": "Project Alpha", "description": "This is the first project." }, { "projectId": "proj_456", "name": "Project Beta", "description": "This is the second project." } ] ``` ```