### Fluxzero CLI help Source: https://fluxzero.io/docs/getting-started/installation Displays the help message for the Fluxzero CLI, outlining all available commands, options, and their usage details. This is useful for discovering the full capabilities of the CLI. ```bash fz -h ``` -------------------------------- ### Manually install Fluxzero CLI Source: https://fluxzero.io/docs/getting-started/installation Provides manual steps for installing the Fluxzero CLI by downloading the JAR file and creating a shell alias. This method is an alternative if the automated script is not preferred or fails. ```bash # 1. Download the latest flux-cli.jar # wget https://repo.fluxzero.io/flux-cli/latest/flux-cli.jar # 2. Place it in your home directory under .flux/flux-cli.jar # mv flux-cli.jar ~/.flux/flux-cli.jar # 3. Create an alias in your shell configuration file (e.g., .bashrc, .zshrc) # echo "alias fz='java -jar ~/.flux/flux-cli.jar $@'" >> ~/.bashrc # or ~/.zshrc # source ~/.bashrc # or source ~/.zshrc ``` -------------------------------- ### Generate a new Fluxzero project with options Source: https://fluxzero.io/docs/getting-started/installation This command generates a new Fluxzero project with specified options directly provided as arguments, bypassing interactive prompts for project metadata and template selection. ```bash fz new --name my-app --group com.example --artifact-id my-app --template basic-java-starter ``` -------------------------------- ### Build a Fluxzero project Source: https://fluxzero.io/docs/getting-started/installation This command is used to build the Fluxzero project after it has been generated and configured. It typically compiles the source code, packages resources, and creates the final application artifact. ```bash fz build ``` -------------------------------- ### Install Fluxzero CLI using Bash script Source: https://fluxzero.io/docs/getting-started/installation This Bash script automates the installation of the Fluxzero CLI. It checks for Java 21+, downloads the latest release, and installs the CLI executable. Optionally, it can add the CLI to the system's PATH. ```bash #!/bin/bash # Check for Java 21+ if ! java -version 2>&1 | grep -q "21."; then echo "Error: Java 21 or higher is required." exit 1 fi # Download the latest Fluxzero CLI release LATEST_CLI_URL="https://repo.fluxzero.io/flux-cli/latest/flux-cli.jar" CLI_DIR="~/.fluxzero/bin" CLI_PATH="$CLI_DIR/fz" if [ ! -d "$CLI_DIR" ]; then mkdir -p "$CLI_DIR" fi echo "Downloading Fluxzero CLI..." wget -qO "$CLI_PATH.jar" "$LATEST_CLI_URL" # Create executable script echo "java -jar $CLI_PATH.jar \$@" > "$CLI_PATH" chmod +x "$CLI_PATH" # Optionally install to /usr/local/bin read -p "Install 'fz' command to /usr/local/bin? (y/N): " install_global if [[ "$install_global" =~ ^[Yy]$ ]]; then if [ -f "/usr/local/bin/fz" ]; then echo "'/usr/local/bin/fz' already exists. Overwriting..." fi sudo ln -sf "$CLI_PATH" "/usr/local/bin/fz" echo "Fluxzero CLI installed globally." else echo "Fluxzero CLI installed in $CLI_PATH." echo "To use it globally, consider adding '$CLI_DIR' to your PATH or creating a symbolic link." fi echo "Fluxzero CLI installation complete." ``` -------------------------------- ### Generate a new Fluxzero project using CLI Source: https://fluxzero.io/docs/getting-started/installation This command initiates the creation of a new Fluxzero project. The CLI will prompt the user for project details such as name, group, artifact ID, and the desired project template. ```bash fz new ``` -------------------------------- ### Test GET /projects Endpoint (Java/Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app Provides an example for testing the `GET /projects` endpoint. This test ensures that the endpoint correctly retrieves and returns a list of projects. ```java TestFixture fixture = new TestFixture(); fixture.when(new HttpGetRequest("/projects")) .expect(new HttpResponse(200, List.of(new Project(), new Project()))); ``` ```kotlin val fixture = TestFixture() fixture.when(HttpGetRequest("/projects")) .expect(HttpResponse(200, listOf(Project(), Project()))) ``` -------------------------------- ### Start New Consumer with minIndex (Java) Source: https://fluxzero.io/docs/guides/messaging/040-message-replays Initiate a replay by defining a new consumer using the @Consumer annotation with a minIndex. This is suitable for starting fresh consumers, bootstrapping projections without impacting live handlers, and encapsulating logic. ```Java @Consumer(minIndex = 100) public class ReplayConsumer { // ... consumer logic ... } ``` -------------------------------- ### Start New Consumer with minIndex (Kotlin) Source: https://fluxzero.io/docs/guides/messaging/040-message-replays Initiate a replay by defining a new consumer using the @Consumer annotation with a minIndex. This is suitable for starting fresh consumers, bootstrapping projections without impacting live handlers, and encapsulating logic. ```Kotlin @Consumer(minIndex = 100) class ReplayConsumer { // ... consumer logic ... } ``` -------------------------------- ### Test Queries (Java/Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app Provides examples for writing tests for queries, specifically `GetProject` and other query types. These tests ensure that queries are correctly retrieving and returning data as expected. ```java TestFixture fixture = new TestFixture(); fixture.when(new GetProjectQuery(...)).expect(new Project(...)); fixture.when(new GetAllProjectsQuery(...)).expect(List.of(new Project(), new Project())); ``` ```kotlin val fixture = TestFixture() fixture.when(GetProjectQuery(...)).expect(Project()) fixture.when(GetAllProjectsQuery()).expect(listOf(Project(), Project())) ``` -------------------------------- ### Create a "Hello World" HTTP Endpoint (Java/Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Provides an example of a simple "Hello World" HTTP endpoint using Fluxzero, demonstrating how to handle HTTP requests with annotations like `@HandleGet`. ```java @HandleGet("/hello") public String sayHello() { return "Hello, World!"; } ``` ```kotlin @HandleGet("/hello") fun sayHello(): String { return "Hello, World!" } ``` -------------------------------- ### Handle Query with Logic (Java) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Java query that handles its own logic, including filtering and authorization based on the sender. ```java package com.example.domain; import com.fluxzero.api.Query; import com.fluxzero.api.Sender; public record GetProject(String id) implements Query { public static GetProject byId(String id) { return new GetProject(id); } public static GetProject byName(String name) { return new GetProject(name); } @HandleQuery public Project handle(ProjectRepository repository, Sender sender) { if (sender.isAdmin()) { return repository.get(id()); } return repository.get(id(), sender.id()); } } ``` -------------------------------- ### Typical REST-like HTTP Endpoint for Project Creation (Java/Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Illustrates a typical REST-like usage for HTTP endpoints, specifically handling a POST request to create a project and a GET request to retrieve it, using path parameters. ```java @HandlePost("/projects") public Project createProject(@Body CreateProjectCommand command) { // Logic to create a project return projectService.createProject(command); } @HandleGet("/projects/{id}") public Project getProject(@PathParam("id") String projectId) { // Logic to retrieve a project return projectService.getProjectById(projectId); } ``` ```kotlin @HandlePost("/projects") fun createProject(@Body command: CreateProjectCommand): Project { // Logic to create a project return projectService.createProject(command) } @HandleGet("/projects/{id}") fun getProject(@PathParam("id") projectId: String): Project { // Logic to retrieve a project return projectService.getProjectById(projectId) } ``` -------------------------------- ### Handle Multiple Commands with Generalization (Java/Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Demonstrates how to handle multiple commands, potentially using interfaces for generalization. This example matches all ProjectUpdate commands and applies them to the matching entity. ```java @HandleCommand public void handleProjectUpdate(ProjectUpdate command, Project entity) { // Apply the update to the project entity entity.apply(command); } ``` ```kotlin @HandleCommand fun handleProjectUpdate(command: ProjectUpdate, entity: Project) { // Apply the update to the project entity entity.apply(command) } ``` -------------------------------- ### React to Events and Publish New Commands (Java/Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Shows how handlers can respond to events published by other system parts. This example reacts to different Project events and triggers new commands. ```java @HandleEvent public void handleProjectCreated(ProjectCreatedEvent event) { // Respond to ProjectCreatedEvent and potentially publish a new command sendCommand(new InitializeProjectCommand(event.getProjectId())); } @HandleEvent public void handleProjectUpdated(ProjectUpdatedEvent event) { // Respond to ProjectUpdatedEvent and potentially publish a new command sendCommand(new NotifyProjectUpdateCommand(event.getProjectId())); } ``` ```kotlin @HandleEvent fun handleProjectCreated(event: ProjectCreatedEvent) { // Respond to ProjectCreatedEvent and potentially publish a new command sendCommand(InitializeProjectCommand(event.projectId)) } @HandleEvent fun handleProjectUpdated(event: ProjectUpdatedEvent) { // Respond to ProjectUpdatedEvent and potentially publish a new command sendCommand(NotifyProjectUpdateCommand(event.projectId)) } ``` -------------------------------- ### Handle Query with Logic (Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Kotlin query that handles its own logic, including filtering and authorization based on the sender. ```kotlin package com.example.domain import com.fluxzero.api.Query import com.fluxzero.api.Sender data class GetProject(val id: String) : Query { companion object { fun byId(id: String): GetProject { return GetProject(id) } fun byName(name: String): GetProject { return GetProject(name) } } @HandleQuery fun handle(repository: ProjectRepository, sender: Sender): Project? { return if (sender.isAdmin()) { repository.get(id) } else { repository.get(id, sender.id) } } } ``` -------------------------------- ### Create Entity Command (Java) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Java command to create a new entity. It injects the current user to establish ownership. ```java package com.example.domain; import com.fluxzero.api.Command; import com.fluxzero.api.Sender; public record CreateProject( String name ) implements Command { @Apply public Project create(Project.Data data, Sender sender) { return new Project(data.id(), sender.id(), data.name()); } } ``` -------------------------------- ### Create Entity Command (Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Kotlin command to create a new entity. It injects the current user to establish ownership. ```kotlin package com.example.domain import com.fluxzero.api.Command import com.fluxzero.api.Sender data class CreateProject(val name: String) : Command { @Apply fun create(data: Project.Data, sender: Sender): Project { return Project(data.id, sender.id, data.name) } } ``` -------------------------------- ### Schedule Handlers Source: https://fluxzero.io/docs/getting-started/core-concepts Guide on using schedule handlers to deliver messages at future times, useful for implementing reminders, retries, and timeouts. ```APIDOC ## Schedule Handlers ### Description Fluxzero allows you to schedule messages for delivery at a specified future time. This feature is valuable for implementing functionalities such as reminders, automatic retries, timeouts, and follow-up actions. ### Use Cases - **Reminders**: Schedule notifications for users. - **Retries**: Automatically retry failed operations. - **Timeouts**: Implement time-based limits for processes. - **Follow-ups**: Schedule subsequent actions based on certain conditions. ### Scheduling a Message Messages can be scheduled for delivery using specific methods, for example, to deliver a message to handlers 2 hours later. ### Example Scenario - **Handler Definition**: Define a handler that processes a specific message type. - **Scheduling the Message**: Use the provided API to schedule the message delivery for a future time. ### Supported Languages - Java - Kotlin ``` -------------------------------- ### Test GET endpoint for querying data (Java) Source: https://fluxzero.io/docs/guides/messaging/140-testing-web-endpoints Tests GET endpoints by first registering a game via POST, then fetching the list of all games via GET and checking the result. Corresponds to a handler method. ```Java // Test for GET /games endpoint // ... test logic ... ``` -------------------------------- ### Manual Document Indexing Example Source: https://fluxzero.io/docs/reference/022-document Illustrates how to manually index documents using the Fluxzero API. This provides explicit control over when and how documents are indexed. ```java // You can manually index documents using the Fluxzero API: // fluxzeroApi.indexDocument(myDocument); ``` -------------------------------- ### Global Fluxzero Instance Setup Source: https://fluxzero.io/docs/guides/configuration--support/310-configuring-fluxzero Shows how to set the configured Fluxzero instance as the global application-wide instance. ```java Fluxzero fluxzero = FluxzeroBuilder.create() .client(webSocketClient) .build(); Fluxzero.setGlobal(fluxzero); ``` -------------------------------- ### Test Project Updates (Java/Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app Provides examples for testing the success and failure scenarios of the UpdateProject command. These tests ensure the command handler behaves as expected under various conditions, verifying the integrity of project updates. ```java TestFixture fixture = new TestFixture(); fixture.when(new UpdateProject(...)).expect(new ProjectUpdated(...)); fixture.when(new UpdateProject(...)).expect(new ProjectUpdateFailed(...)); ``` ```kotlin val fixture = TestFixture() fixture.when(UpdateProject(...)).expect(ProjectUpdated(...)) fixture.when(UpdateProject(...)).expect(ProjectUpdateFailed(...)) ``` -------------------------------- ### Serve React app with fallback Source: https://fluxzero.io/docs/guides/messaging/120-handling-web-requests Example of serving a single-page application (like React) by serving static assets and providing a fallback file for client-side routing. ```java @ServeStatic(uriPath = "/app/**", resourcePath = "/static", fallbackFile = "index.html") // Serves /app/index.html, /app/main.js, etc. from /static // Falls back to index.html for client-side routing ``` -------------------------------- ### Send Command with Metadata (Java) Source: https://fluxzero.io/docs/guides/messaging/020-message-handling An example in Java showing how to send a command with metadata, which includes key-value context like correlation IDs. ```java import java.util.HashMap; import java.util.Map; public class CommandSender { public void sendCommandWithMeta(String userId) { Map metadata = new HashMap<>(); metadata.put("correlationId", "abc-123"); metadata.put("userAgent", "TestClient"); MyCommand command = new MyCommand(userId); command.setMetadata(metadata); Fluxzero.sendCommand(command); } } ``` -------------------------------- ### Testing Events Source: https://fluxzero.io/docs/reference/025-event Provides examples of how to test event publishing and handling logic. This includes verifying that the correct events are published and that handlers process them as expected. ```java testPublisher.publishEvent(new TestEvent()); assertThat(testHandler.getLastEvent()).isInstanceOf(TestEvent.class); ``` ```kotlin testPublisher.publishEvent(TestEvent()) assertThat(testHandler.lastEvent).isInstanceOf(TestEvent::class.java) ``` -------------------------------- ### Schedule a Reminder Message (Java/Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Demonstrates how to schedule messages to be delivered at a specific time in the future, using an example of sending a reminder message 2 hours later. ```java // Handler that receives the scheduled message @HandleSchedule public void handleReminder(ReminderMessage message) { System.out.println("Reminder: " + message.getContent()); } // Code to schedule the message @Inject private Scheduler scheduler; public void sendReminderLater(String content) { ReminderMessage reminder = new ReminderMessage(content); scheduler.schedule(reminder, 2, TimeUnit.HOURS); } ``` ```kotlin // Handler that receives the scheduled message @HandleSchedule fun handleReminder(message: ReminderMessage) { println("Reminder: ${message.content}") } // Code to schedule the message @Inject private lateinit var scheduler: Scheduler fun sendReminderLater(content: String) { val reminder = ReminderMessage(content) scheduler.schedule(reminder, 2, TimeUnit.HOURS) } ``` -------------------------------- ### Send Command with Metadata (Kotlin) Source: https://fluxzero.io/docs/guides/messaging/020-message-handling An example in Kotlin showing how to send a command with metadata, which includes key-value context like correlation IDs. ```kotlin class CommandSender { fun sendCommandWithMeta(userId: String) { val metadata = mapOf( "correlationId" to "abc-123", "userAgent" to "TestClient" ) val command = MyCommand(userId) command.metadata = metadata Fluxzero.sendCommand(command) } } ``` -------------------------------- ### Add a Task to a Project in Java and Kotlin Source: https://fluxzero.io/docs/getting-started/core-concepts Provides code examples for adding a task to a project, likely involving entity updates and event handling in Java and Kotlin. ```java public class Project { private List tasks = new ArrayList<>(); public void addTask(Task task) { tasks.add(task); } // ... other methods } ``` ```kotlin class Project { private val tasks: MutableList = mutableListOf() fun addTask(task: Task) { tasks.add(task) } // ... other methods } ``` -------------------------------- ### Initialize Project Tasks List (Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app Initializes the tasks list for a new Project to be empty upon creation in Kotlin. This ensures every Project starts without any tasks. ```Kotlin data class CreateProject(val name: String) : ProjectCommand { override fun applyOn(project: Project): Project = Project(name) } ``` -------------------------------- ### Automatic Document Indexing Example Source: https://fluxzero.io/docs/reference/022-document Demonstrates automatic indexing of documents when a class is marked with the `@Searchable` annotation. This simplifies the indexing process by handling it implicitly. ```java // For classes marked with @Searchable, indexing happens automatically: // @Searchable // public class MyDocument { ... } ``` -------------------------------- ### Query with Explicit Return Type (Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Kotlin query specifying its return type using a Request interface for compile-time safety. ```kotlin package com.example.domain import com.fluxzero.api.Query import com.fluxzero.api.Request data class GetProjectDetailsQuery(val projectId: String) : Request { @HandleQuery fun handle(repository: ProjectRepository): ProjectDetails { val project = repository.get(projectId) return ProjectDetails(project.id, project.name) } } ``` -------------------------------- ### Apply Updates to Entities in Java Source: https://fluxzero.io/docs/guides/modeling--persistence/170-domain-modeling Provides Java code examples for commands that evolve entities by applying validated changes. It shows a command to create a user and another to update their profile. ```java import io.fluxzero.Apply; public class UserCommands { public record CreateUser(String userId, String email) {} @Apply public UserAggregate createUser(CreateUser command, UserAggregate aggregate) { // logic to create user return aggregate; } public record UpdateProfile(String userId, String newName) {} @Apply public UserAggregate updateProfile(UpdateProfile command, UserAggregate aggregate) { // logic to update profile return aggregate; } } ``` -------------------------------- ### Handle User Creation Event and Dispatch Command (Java) Source: https://fluxzero.io/docs/guides/messaging/020-message-handling An example of an event handler in Java that dispatches a command to send a welcome email when a user is created. It uses the static sendCommand method, leveraging automatic client injection. ```java public class UserEventHandler { @HandleEvent public void onUserCreated(UserCreatedEvent event) { Fluxzero.sendCommand(new SendWelcomeEmailCommand(event.getUserId())); } } ``` -------------------------------- ### Query with Explicit Return Type (Java) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Java query specifying its return type using a Request interface for compile-time safety. ```java package com.example.domain; import com.fluxzero.api.Query; import com.fluxzero.api.Request; public record GetProjectDetails(String projectId) implements Request { @HandleQuery public ProjectDetails handle(ProjectRepository repository) { Project project = repository.get(projectId); return new ProjectDetails(project.id(), project.name()); } } ``` -------------------------------- ### Handle User Creation Event and Dispatch Command (Kotlin) Source: https://fluxzero.io/docs/guides/messaging/020-message-handling An example of an event handler in Kotlin that dispatches a command to send a welcome email when a user is created. It uses the static sendCommand method, leveraging automatic client injection. ```kotlin class UserEventHandler { @HandleEvent fun onUserCreated(event: UserCreatedEvent) { Fluxzero.sendCommand(SendWelcomeEmailCommand(event.userId)) } } ``` -------------------------------- ### Upsert Entity Command (Java) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Java command to upsert (create or update) an entity. Fluxzero handles invoking the correct @Apply method based on entity existence. ```java package com.example.domain; import com.fluxzero.api.Command; import com.fluxzero.api.Sender; public record UpsertProject( String name ) implements Command { @Apply public Project create(Project.Data data, Sender sender) { return new Project(data.id(), sender.id(), data.name()); } @Apply public Project update(Project project, Project.Data data) { return project.withName(data.name()); } } ``` -------------------------------- ### Upsert Entity Command (Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Kotlin command to upsert (create or update) an entity. Fluxzero handles invoking the correct @Apply method based on entity existence. ```kotlin package com.example.domain import com.fluxzero.api.Command import com.fluxzero.api.Sender data class UpsertProject(val name: String) : Command { @Apply fun create(data: Project.Data, sender: Sender): Project { return Project(data.id, sender.id, data.name) } @Apply fun update(project: Project, data: Project.Data): Project { return project.withName(data.name) } } ``` -------------------------------- ### Basic Document Search Example Source: https://fluxzero.io/docs/reference/022-document Shows a basic search operation using the Fluxzero search API for querying documents. This is a fundamental operation for retrieving data stored as documents. ```java // Fluxzero provides a powerful search API for querying documents: // List results = fluxzeroApi.search("query"); ``` -------------------------------- ### Querying Projects Source: https://fluxzero.io/docs/tutorials/first-app Shows how to query stored projects, including implementing filtering and authorization logic. ```APIDOC ## Querying Projects ### Description Demonstrates how to query project data, including implementing custom logic for filtering and authorization within query classes. ### Method Not Applicable (Code example) ### Endpoint Not Applicable ### Parameters Not Applicable ### Request Example Not Applicable ### Response Not Applicable ### Code Examples **Java (Direct Handling):** ```java class GetProjectsQuery { public List handle() { // query logic return projects; } } ``` **Kotlin (Direct Handling):** ```kotlin class GetProjectsQuery { fun handle(): List { // query logic return projects } } ``` **Java (With Authorization):** ```java class GetProjectByIdQuery { public Project handle(String projectId, User sender) { return repository.getProjectById(projectId, sender); } } // In repository: Project getProjectById(String projectId, User sender) { return findById(projectId).match(p -> sender.canView(p)); } ``` **Kotlin (With Authorization):** ```kotlin class GetProjectByIdQuery { fun handle(projectId: String, sender: User): Project { return repository.getProjectById(projectId, sender) } } // In repository: fun getProjectById(projectId: String, sender: User): Project? { return findById(projectId)?.match { sender.canView(it) } } ``` ``` -------------------------------- ### Handle GET requests for /users Source: https://fluxzero.io/docs/guides/messaging/120-handling-web-requests Handles incoming GET requests to the /users URI and returns a list of users as a WebResponse. This is a common pattern for retrieving data. ```java @HandleGet("/users") List getUsers() { return userService.findAll(); } ``` ```kotlin @HandleGet("/users") fun getUsers(): List { return userService.findAll() } ``` -------------------------------- ### Test CreateProject command in Java and Kotlin Source: https://fluxzero.io/docs/tutorials/first-app Shows how to write behavior tests for the CreateProject command, verifying that the command payload is correctly applied and published as an event. ```java testFixture.givenNoState() .whenCommand(new CreateProject("1", "user1", "MyProject")) .expectApply("1", new Project("1", "user1", "MyProject")); ``` ```kotlin testFixture.givenNoState() .whenCommand(CreateProject("1", "user1", "MyProject")) .expectApply("1", Project("1", "user1", "MyProject")) ``` -------------------------------- ### Document vs Event Sourcing Decision Guide Source: https://fluxzero.io/docs/reference/022-document This guide helps decide between Fluxzero's Document storage and Event Sourcing based on use case requirements. Documents are suited for read-heavy workloads and full-text search, while Event Sourcing is preferred for audit trails and complex state transitions. ```text **Use Event Sourcing when** : * You need complete audit trails * Business logic requires knowing what happened when * Compliance or regulatory requirements * Complex domain logic with many state transitions **Use Documents when** : * Read-heavy workloads (catalogs, references) * Full-text search is primary use case * Current state is more important than history * Performance over auditability ``` -------------------------------- ### Full-Text Search Implementation Source: https://fluxzero.io/docs/tutorials/first-app Explains how to implement full-text search and autocomplete features for queries using Fluxzero's search capabilities. ```APIDOC ## Full-Text Search Implementation ### Description Provides an example of implementing full-text search and lookahead behavior within queries using Fluxzero's integrated search functionality. ### Method Not Applicable (Code example) ### Endpoint Not Applicable ### Parameters Not Applicable ### Request Example Not Applicable ### Response Not Applicable ### Code Examples **Java:** ```java class SearchProjectsQuery { public List handle(String query) { return projectRepository.search(query).lookAhead(Project::getName); } } ``` **Kotlin:** ```kotlin class SearchProjectsQuery { fun handle(query: String): List { return projectRepository.search(query).lookAhead { it.name } } } ``` ``` -------------------------------- ### Create Project using @Apply in Java and Kotlin Source: https://fluxzero.io/docs/tutorials/first-app Demonstrates how to use the @Apply method to create a new Project entity. It shows how to inject context, such as the user initiating the command, to set the Project's owner. ```java Project project = new Project(projectId, ownerId, projectName); apply(project); ``` ```kotlin val project = Project(projectId, ownerId, projectName) apply(project) ``` -------------------------------- ### Read Metadata in Handler (Kotlin) Source: https://fluxzero.io/docs/guides/messaging/020-message-handling An example in Kotlin demonstrating how to read metadata within a handler method. ```kotlin class MetadataHandler { @HandleCommand fun handleCommandWithMetadata(command: MyCommand) { val correlationId = command.metadata["correlationId"] println("Received command with correlationId: $correlationId") // Process command... } } ``` -------------------------------- ### Perform Optimized Range Query with Sorting Source: https://fluxzero.io/docs/guides/modeling--persistence/220-document-index-and-search Example of performing a fast, index-backed range query using @Sortable fields. This query targets products within a specific price range and sorts them by release date. ```java Fluxzero.search(Product.class) .between(Product::getPrice, Money.ofMinor(1000, EUR), Money.ofMinor(10000, EUR)) .sort(Product::getReleaseDate) .fetch(); ``` -------------------------------- ### Read Metadata in Handler (Java) Source: https://fluxzero.io/docs/guides/messaging/020-message-handling An example in Java demonstrating how to read metadata within a handler method. ```java import java.util.Map; public class MetadataHandler { @HandleCommand public void handleCommandWithMetadata(MyCommand command) { Map metadata = command.getMetadata(); String correlationId = metadata.get("correlationId"); System.out.println("Received command with correlationId: " + correlationId); // Process command... } } ``` -------------------------------- ### Define CreateProject Command (Java) Source: https://fluxzero.io/docs/tutorials/first-app Defines the `CreateProject` command for creating a new project. It's a simple record containing the project ID and details. ```java package com.example.todo; import fluxzero.Command; public record CreateProject( Project.ProjectId projectId, ProjectDetails details ) implements Command { } ``` -------------------------------- ### Return CompletableFuture from Handler (Kotlin) Source: https://fluxzero.io/docs/guides/messaging/020-message-handling An example of a handler method in Kotlin that returns a CompletableFuture. Fluxzero will publish the result when the future completes. ```kotlin import kotlinx.coroutines.future.await import java.util.concurrent.CompletableFuture class AsyncQueryHandler { @HandleQuery fun handleGetAsyncData(query: GetAsyncDataQuery): CompletableFuture { return CompletableFuture.supplyAsync { // Simulate async data fetching Thread.sleep(1000) "Async data for ${query.key}" } } } ``` -------------------------------- ### Basic Fluxzero Instance Configuration Source: https://fluxzero.io/docs/guides/configuration--support/310-configuring-fluxzero Demonstrates the default way to configure and build a Fluxzero instance. ```java Fluxzero fluxzero = FluxzeroBuilder.create() .client(webSocketClient) .build(); ``` -------------------------------- ### Return CompletableFuture from Handler (Java) Source: https://fluxzero.io/docs/guides/messaging/020-message-handling An example of a handler method in Java that returns a CompletableFuture. Fluxzero will publish the result when the future completes. ```java import java.util.concurrent.CompletableFuture; public class AsyncQueryHandler { @HandleQuery public CompletableFuture handleGetAsyncData(GetAsyncDataQuery query) { return CompletableFuture.supplyAsync(() -> { // Simulate async data fetching try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Async data for " + query.getKey(); }); } } ``` -------------------------------- ### Handling Commands Source: https://fluxzero.io/docs/getting-started/core-concepts Details on how to create handlers for commands, including applying commands to entities, asserting legality, and publishing events. ```APIDOC ## Handling Commands ### Description This section details how to create command handlers that apply commands to matching entities. It covers loading entity state, asserting legality, applying changes, and publishing events upon successful command acceptance. ### Key Actions - **Load Entity**: Retrieve the current state of an entity using `loadEntity()`. - **Assert and Apply**: Use `assertAndApply(command)` on the entity. - Executes `@AssertLegal` methods within the command. - Calls the matching `@Apply` method. - Publishes an event with the same payload upon success. ### Handling Multiple Commands Generalize logic across commands using interfaces to handle multiple command types with a single handler. Customize behavior for specific commands by overriding defaults. ### Supported Languages - Java - Kotlin ``` -------------------------------- ### Register MappingBatchInterceptor Globally Source: https://fluxzero.io/docs/guides/configuration--support/300-message-interceptors Explains how to install a MappingBatchInterceptor globally. This interceptor specialization allows for rewriting or filtering the message batch itself. ```java FluxzeroBuilder builder = Fluxzero.builder(); builder.addInterceptor(new MyMappingBatchInterceptor()); ``` -------------------------------- ### Query Project with Access Control (Java/Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app Illustrates how to implement access control within a query to restrict data visibility based on the sender. It demonstrates fetching a Project with filtering logic, allowing admins to view all results by passing null to `.match()`. ```java class GetProjectQuery { // ... constructor and other methods public Project handle() { return sender.query(Project.class) .where(p -> p.getOwnerId().equals(sender.getUserId())) .match(null) // Allow admins to bypass filter .get(); } } ``` ```kotlin class GetProjectQuery(private val sender: Sender) { // ... constructor and other methods fun handle(): Project { return sender.query(Project::class) .where { it.ownerId == sender.userId } .match(null) // Allow admins to bypass filter .get() } } ``` -------------------------------- ### Apply Command to Entity (Java) Source: https://fluxzero.io/docs/tutorials/first-app Demonstrates loading an entity by its ID and applying a command to it, handling both existing and non-existing entities. ```java package com.example.todo; import fluxzero.CommandHandler; import fluxzero.Entity; import fluxzero.Fluxzero; public class ProjectCommandHandler implements CommandHandler { private final Fluxzero fluxzero; public ProjectCommandHandler(Fluxzero fluxzero) { this.fluxzero = fluxzero; } public void handle(CreateProject command) { Entity project = fluxzero.load(command.projectId(), Project.class); project.apply(command); fluxzero.save(project); } } ``` -------------------------------- ### Fluxzero Core Concepts Overview Source: https://fluxzero.io/docs/getting-started/core-concepts This section provides an overview of the fundamental building blocks in Fluxzero applications. ```APIDOC ## Core Concepts Fluxzero apps are built with **clean, expressive code** — no scaffolding, no layers, no dependency injection. Just logic. You write the heart of your application: the messages, logic, and state. Fluxzero handles everything else: delivery, persistence, routing, retries, observability, and scale. ### What you write These are the core building blocks of your business logic — all plain Java or Kotlin classes: | Concept | Description | Example | |----------|------------------------------------------------|-----------------| | **Command** | A request to change state | `DepositMoney` | | **Query** | A request for information | `GetAccountBalance` | | **Handler** | Responds to messages like commands | `@HandleCommand DepositMoney` | | **Endpoint**| Handler that responds to HTTP requests | `@HandleGet("/account/{id}")` | | **Entity** | Evolving object that holds state | `BankAccount` | | **Test** | Verifies business flows | `fixture.whenCommand(...)` | ``` -------------------------------- ### Handle CreateProject Command (Java) Source: https://fluxzero.io/docs/tutorials/first-app A message handler that listens for `CreateProject` commands and applies them to the target `Project` entity. ```java package com.example.todo; import fluxzero.CommandHandler; import fluxzero.Entity; import fluxzero.Fluxzero; public class ProjectCommandHandler implements CommandHandler { private final Fluxzero fluxzero; public ProjectCommandHandler(Fluxzero fluxzero) { this.fluxzero = fluxzero; } public void handle(CreateProject command) { fluxzero.apply(command.projectId(), command); } } ``` -------------------------------- ### Update Project Command Handler Source: https://fluxzero.io/docs/tutorials/first-app Demonstrates updating the command handler to manage various project commands by extracting a shared interface. ```APIDOC ## Update Project Command Handler ### Description Update the command handler to process various project-related commands, such as CreateProject and UpdateProject, by implementing a shared interface. ### Method Not Applicable (Code example) ### Endpoint Not Applicable ### Parameters Not Applicable ### Request Example Not Applicable ### Response Not Applicable ### Code Examples **Java:** ```java // Shared interface interface ProjectCommand { // common methods } // Implementation class CreateProject implements ProjectCommand { ... } class UpdateProject implements ProjectCommand { ... } // Handler update class ProjectCommandHandler { public void handle(ProjectCommand command) { // logic to handle different command types } } ``` **Kotlin:** ```kotlin // Shared interface interface ProjectCommand { // common methods } // Implementation class CreateProject : ProjectCommand { ... } class UpdateProject : ProjectCommand { ... } // Handler update class ProjectCommandHandler { fun handle(command: ProjectCommand) { // logic to handle different command types } } ``` ``` -------------------------------- ### Delete Entity Command (Kotlin) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Kotlin command to delete an entity. Deletion is achieved by returning null from the @Apply method. ```kotlin package com.example.domain import com.fluxzero.api.Command object DeleteProject : Command { @Apply fun apply(): Project? { return null } } ``` -------------------------------- ### Adding an HTTP Endpoint Source: https://fluxzero.io/docs/tutorials/first-app Details how to expose domain logic over HTTP by defining handlers that map to standard REST-style routes. ```APIDOC ## Adding an HTTP Endpoint ### Description Demonstrates how to expose application logic via HTTP endpoints using Fluxzero's annotation-based routing. ### Method Not Applicable (Code example) ### Endpoint Not Applicable ### Parameters Not Applicable ### Request Example Not Applicable ### Response Not Applicable ### Code Examples **Java:** ```java @HttpEndpoint public class ProjectEndpoint { @HandlePost("/projects") public void createProject(@RequestBody CreateProjectCommand command) { // command handling logic } @HandleGet("/projects/{projectId}") public Project getProject(@PathParam("projectId") String id) { // query logic return projectRepository.getProjectById(id); } } ``` **Kotlin:** ```kotlin @HttpEndpoint class ProjectEndpoint { @HandlePost("/projects") fun createProject(@RequestBody command: CreateProjectCommand) { // command handling logic } @HandleGet("/projects/{projectId}") fun getProject(@PathParam("projectId") id: String): Project { // query logic return projectRepository.getProjectById(id) } } ``` ``` -------------------------------- ### Delete Entity Command (Java) Source: https://fluxzero.io/docs/getting-started/core-concepts Example of a Java command to delete an entity. Deletion is achieved by returning null from the @Apply method. ```java package com.example.domain; import com.fluxzero.api.Command; public record DeleteProject() implements Command { @Apply public Project apply() { return null; } } ``` -------------------------------- ### Apply Command to Entity (Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app Shows how to load an entity using its ID and apply a command to it in Kotlin, including saving the updated entity. ```kotlin package com.example.todo import fluxzero.CommandHandler import fluxzero.Entity import fluxzero.Fluxzero class ProjectCommandHandler(private val fluxzero: Fluxzero) : CommandHandler { fun handle(command: CreateProject) { val project: Entity = fluxzero.load(command.projectId, Project::class.java) project.apply(command) fluxzero.save(project) } } ``` -------------------------------- ### Full-text Search and Composing Queries Source: https://fluxzero.io/docs/getting-started/core-concepts Learn how to implement out-of-the-box full-text search with lookahead behavior and compose queries by calling other queries like functions for logic reuse and filtering. ```APIDOC ## Full-text Search and Composing Queries ### Description Fluxzero's search is full-text and autocomplete-ready. You can use methods like `.match()` and `.lookAhead()` without any configuration. Queries can also call other queries, similar to functions, enabling logic reuse, result filtering, and assembling responses from multiple sources. ### Key Features - **Full-text Search**: Built-in full-text search with autocomplete capabilities. - **Lookahead Behavior**: Implement lookahead functionality easily. - **Query Composition**: Reuse query logic by composing them like functions. - **No Configuration Needed**: Features are available out-of-the-box. ### Supported Languages - Java - Kotlin ``` -------------------------------- ### Define CreateProject Command (Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app Defines the `CreateProject` command for creating a new project in Kotlin. It's a data class holding the project ID and details. ```kotlin package com.example.todo import fluxzero.Command data class CreateProject( val projectId: Project.ProjectId, val details: ProjectDetails ) : Command ``` -------------------------------- ### Type-Safe Query Test (Java) Source: https://fluxzero.io/docs/guides/messaging/065-response-typing Provides an example of a type-safe test in Java for a query, leveraging the inferred response type from the `Request` interface. ```Java MyResponse response = queryAndWait(new MyQuery()); assertEquals(expectedResponse, response); ``` -------------------------------- ### Testing HTTP Endpoints Source: https://fluxzero.io/docs/tutorials/first-app Explains how to test HTTP endpoint behavior, including mixing commands and HTTP calls within tests and chaining test phases. ```APIDOC ## Testing HTTP Endpoints ### Description Provides guidance and examples on testing HTTP endpoint functionality, including integration with commands and queries, and advanced test chaining. ### Method Not Applicable (Code example) ### Endpoint Not Applicable ### Parameters Not Applicable ### Request Example Not Applicable ### Response Not Applicable ### Code Examples **Java (Testing Create Project):** ```java @Test void testCreateProjectEndpoint() { testFixture.forHttp() // Use forHttp() for HTTP endpoint testing .given(ProjectCommandHandler.class) .when(HttpRequest.post("/projects").withBody(new CreateProjectCommand(...))) .then(published(ProjectCreatedEvent.class)); } ``` **Kotlin (Testing Create Project):** ```kotlin @Test fun testCreateProjectEndpoint() { testFixture.forHttp() .given(ProjectCommandHandler::class.java) .when(HttpRequest.post("/projects").withBody(CreateProjectCommand(...))) .then(published(ProjectCreatedEvent::class.java)) } ``` **Java (Chaining Test Phases):** ```java testFixture.forHttp() .given(ProjectCommandHandler.class) .when(HttpRequest.post("/projects").withBody(new CreateProjectCommand(...))) .then(published(ProjectCreatedEvent.class)) .andThen(HttpRequest.get("/projects/{projectId}")) // {projectId} is auto-filled .then(assertThat(response -> response.statusCode() == 200)); ``` **Kotlin (Chaining Test Phases):** ```kotlin testFixture.forHttp() .given(ProjectCommandHandler::class.java) .when(HttpRequest.post("/projects").withBody(CreateProjectCommand(...))) .then(published(ProjectCreatedEvent::class.java)) .andThen(HttpRequest.get("/projects/{projectId}")) // {projectId} is auto-filled .then { assertThat(it.statusCode() == 200) } ``` **Java (Testing Get Projects):** ```java @Test void testGetProjectsEndpoint() { testFixture.forHttp() .when(HttpRequest.get("/projects")) .then(payload(projects -> { assertThat(projects).hasSize(1); assertThat(projects.get(0).getName()).isEqualTo("Test Project"); })); } ``` **Kotlin (Testing Get Projects):** ```kotlin @Test fun testGetProjectsEndpoint() { testFixture.forHttp() .when(HttpRequest.get("/projects")) .then { payload -> assertThat(payload).hasSize(1) assertThat(payload[0].name).isEqualTo("Test Project") } } ``` ``` -------------------------------- ### Implement Lookahead Search (Java/Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app Shows how to implement lookahead behavior for full-text search using Fluxzero's search capabilities. It highlights the use of methods like `.match()` and `.lookAhead()` for creating responsive search functionalities without additional configuration. ```java class ProjectSearchQuery implements Request> { // ... query implementation public List handle() { return sender.search(Project.class) .match("query") .lookAhead(true) .get(); } } ``` ```kotlin class ProjectSearchQuery(private val sender: Sender) : Request> { // ... query implementation fun handle(): List { return sender.search(Project::class) .match("query") .lookAhead(true) .get() } } ``` -------------------------------- ### Example of Entity Lookup with @Alias Source: https://fluxzero.io/docs/guides/modeling--persistence/190-nested-entities Shows how to look up a UserAccount entity using its alias, illustrating the practical application of the @Alias annotation. ```Java UserAccount account = repository.load(externalId("user-123")); ``` -------------------------------- ### Handle CreateProject Command (Kotlin) Source: https://fluxzero.io/docs/tutorials/first-app A message handler in Kotlin that processes `CreateProject` commands by applying them to the relevant `Project` entity. ```kotlin package com.example.todo import fluxzero.CommandHandler import fluxzero.Entity import fluxzero.Fluxzero class ProjectCommandHandler(private val fluxzero: Fluxzero) : CommandHandler { fun handle(command: CreateProject) { fluxzero.apply(command.projectId, command) } } ``` -------------------------------- ### Test a Command Flow in Java and Kotlin Source: https://fluxzero.io/docs/getting-started/core-concepts Demonstrates how to write behavioral tests for command flows, simulating command execution and verifying expected outcomes like applied commands and published events, using a `given → when → then` structure in Java and Kotlin. ```java import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class ProjectCommandTest { @Test void shouldCreateProjectAndPublishEvent() { testKit.run( given(() -> new CreateProject("New Project")) .when(CreateProject.class, CreateProject::new) .then(expectApplied(CreateProject.class), expectPublished(ProjectCreated.class)) ); } } ``` ```kotlin import org.junit.jupiter.api.Test class ProjectCommandTest { @Test fun `should create project and publish event`() { testKit.run { given(CreateProject("New Project")) .when(CreateProject::class) { CreateProject(it.name) } .then(expectApplied(), expectPublished()) } } } ```