### Basic AxonTestFixture Setup Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Demonstrates the basic setup of AxonTestFixture for testing command handlers. It shows how to create a fixture from ApplicationConfigurer and execute a command. ```java import io.axoniq.axonserver.connector.AxonServerConfiguration; import org.axonframework.config.Configuration; import org.axonframework.config.DefaultConfigurer; import org.axonframework.test.AxonTester; import org.axonframework.test.AxonTestFixture; public class MyTest { @Test public void testMyCommandHandler() { AxonTestFixture fixture = new AxonTestFixture(MyCommand.class, MyEvent.class); fixture.givenNoPriorActivity() .when(new MyCommand("some-id", "some-payload")) .expectSuccessfulHandlerExecution() .expectEvents("some-event"); } } ``` -------------------------------- ### Spring Boot Configuration Example Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Axon Query components can be auto-configured when using Spring Boot. Ensure the necessary dependencies are present for automatic setup of QueryBus and QueryGateway. ```java public class MyAxonConfig { // Auto-configuration handles QueryBus and QueryGateway setup } ``` -------------------------------- ### Axon Framework 5 AxonTestFixture Setup with ApplicationConfigurer Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/test-fixtures.adoc Illustrates the Axon Framework 5 setup using AxonTestFixture, which is built from an ApplicationConfigurer, ensuring consistent configuration between tests and production. ```java import org.axonframework.common.configuration.ApplicationConfigurer; import org.axonframework.eventsourcing.configuration.EventSourcedEntityModule; import org.axonframework.eventsourcing.configuration.EventSourcingConfigurer; import org.axonframework.messaging.core.configuration.MessagingConfigurer; import org.axonframework.test.fixture.AxonTestFixture; import org.junit.jupiter.api.*; class GiftCardTest { private AxonTestFixture testFixture; @BeforeEach void setUp() { // Reuse of the ApplicationConfigurer, ensuring components are configured once: ApplicationConfigurer configurer = AxonConfig.appConfigurer(); testFixture = AxonTestFixture.with(configurer); } } class AxonConfig { // Static construction is an example for ApplicationConfigurer reuse in tests, but not mandatory public static ApplicationConfigurer appConfigurer() { return EventSourcingConfigurer.create() .registerEntity(giftCardModule()) .messaging(AxonConfig::messagingCustomization); } private static EventSourcedEntityModule giftCardModule() { return EventSourcedEntityModule.autodetected(String.class, GiftCard.class); } private static MessagingConfigurer messagingCustomization(MessagingConfigurer configurer) { return configurer.registerCommandHandlerInterceptor( c -> new MyCommandHandlingInterceptor() ); } } ``` -------------------------------- ### Complete Parameter Injection Example Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Provides a comprehensive example showcasing the injection of various parameters available in command handlers, including command payload, EventAppender, ProcessingContext, and @MetadataValue. ```java @CommandHandler public void handle(MyCommand command, EventAppender appender, ProcessingContext context, CommandDispatcher dispatcher, QueryDispatcher queryDispatcher, @MetadataValue("correlationId") String correlationId, @MetadataValue("userId") String userId) { // Use all injected parameters } ``` -------------------------------- ### Custom Setup with Execute in Test Fixture Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/testing/pages/basic-testing.adoc Utilize the `execute(Function)` method for complex setup scenarios, granting access to the entire `Configuration`. This is useful for setting up external state or dependencies. ```java import org.axonframework.modelling.repository.Repository; import org.axonframework.test.fixture.AxonTestFixture; class AccountTest { private AxonTestFixture fixture; @Test void test() { fixture.given() .execute(config -> { // Access any component from configuration var repository = config.getComponent(Repository.class); // Perform custom setup }); // when... } } ``` -------------------------------- ### REST Controller Example with CommandGateway Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Example of a REST controller using CommandGateway to send commands. This demonstrates a practical use case in a web application. ```java @RestController public class MyController { private final CommandGateway commandGateway; public MyController(CommandGateway commandGateway) { this.commandGateway = commandGateway; } @PostMapping("/my-command") public void handleCommand(@RequestBody MyCommand command) { commandGateway.sendAndForget(command); } } ``` -------------------------------- ### Asynchronous Custom Setup with ExecuteAsync in Test Fixture Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/testing/pages/basic-testing.adoc Employ `executeAsync(Function>)` for asynchronous custom setup logic within the test fixture. This method allows returning a `CompletableFuture` for async operations. ```java import org.axonframework.test.fixture.AxonTestFixture; import org.junit.jupiter.api.*; import java.util.concurrent.CompletableFuture; class AccountTest { private AxonTestFixture fixture; @Test void test() { fixture.given() .executeAsync(config -> { // Return CompletableFuture return CompletableFuture.supplyAsync(() -> { // Async setup logic return null; }); }); // when... } } ``` -------------------------------- ### Instance Handler Example Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Demonstrates an instance command handler, which is an instance method on an entity or a method that takes the entity as a parameter. ```java @EventSourcedEntity public class MyEntity { @CommandHandler public void handle(UpdateMyEntityCommand command, EventAppender appender) { // Handle the command on an existing entity instance } } ``` -------------------------------- ### Axon Framework 4 AggregateTestFixture Setup Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/test-fixtures.adoc Demonstrates the setup of AggregateTestFixture in Axon Framework 4, requiring manual registration of components like command handler interceptors. ```java import org.axonframework.test.aggregate.AggregateTestFixture; import org.axonframework.test.aggregate.FixtureConfiguration; import org.junit.jupiter.api.*; class GiftCardTest { private FixtureConfiguration testFixture; @BeforeEach void setUp() { // The MyCommandHandlingInterceptor configuration is duplicated for the fixture: testFixture = new AggregateTestFixture<>(GiftCard.class) .registerCommandHandlerInterceptor(new MyCommandHandlingInterceptor()); } } ``` -------------------------------- ### Axon 5 DispatchInterceptor Example Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/interceptors.adoc Example of a MessageDispatchInterceptor in Axon Framework 5, demonstrating async-first processing with MessageStream and explicit ProcessingContext. ```java public class MyDispatchInterceptor implements MessageDispatchInterceptor { @Override public MessageStream interceptOnDispatch(CommandMessage message, @Nullable ProcessingContext context, MessageDispatchInterceptorChain chain) { // Modify or enrich message CommandMessage enrichedMessage = message.andMetaData( Collections.singletonMap("dispatchTime", Instant.now()) ); // Continue chain with modified message return chain.proceed(enrichedMessage, context); } } ``` -------------------------------- ### Transaction Interceptor Example with Resource Management Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/messaging-concepts/pages/processing-context.adoc An advanced example demonstrating a `TransactionInterceptor` that manages a `Transaction` resource using a type-safe `ResourceKey`. This pattern is useful for custom storage solutions not supported out-of-the-box by Axon Framework. ```java // Note that this is an advanced example! // Axon Framework typically deals with transaction and connection details for you, so you don't have too. // That makes thi example useful ONLY if you are using a storage solution that is not supported by Axon Framework out of the box. public class TransactionInterceptor implements MessageHandlerInterceptor { private static final ResourceKey TX_KEY = ResourceKey.withLabel("Transaction"); @Override public MessageStream interceptOnHandle( CommandMessage command, ProcessingContext context, ``` -------------------------------- ### Implementing a Custom RoutingStrategy Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Example of implementing a custom RoutingStrategy to define a specific routing logic for commands. ```java public class MyCustomRoutingStrategy implements RoutingStrategy { @Override public RoutingKey determineRoutingKey(CommandMessage command) { // Custom logic to determine the routing key return RoutingKey.create("myCustomKey"); } } ``` -------------------------------- ### Registering a StatefulCommandHandlingModule Source: https://github.com/axoniq/axonframework/blob/main/axon-5/api-changes.md This example shows how to register a StatefulCommandHandlingModule using the ModellingConfigurer. Further module-specific configurations can be added after naming the module. ```java public static void main(String[] args) { ModellingConfigurer.create() .registerStatefulCommandHandlingModule( StatefulCommandHandlingModule.named("my-module") // Further MODULE configuration... ); // Further configuration... } ``` -------------------------------- ### AxonTestFixture Setup without Spring Boot Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/testing/pages/basic-testing.adoc Initializes AxonTestFixture with a custom Axon configurer. Ensure to stop the fixture after use. ```java import org.axonframework.test.fixture.AxonTestFixture; import org.junit.jupiter.api.*; class AccountTest { private AxonTestFixture fixture; @BeforeEach void setUp() { fixture = AxonTestFixture.with(AxonConfig.configurer()); } @AfterEach void tearDown() { fixture.stop(); // Always stop the fixture! } // tests... ``` -------------------------------- ### Configuring Interceptors with MessagingConfigurer Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Demonstrates how to configure message dispatch and handler interceptors using `MessagingConfigurer`. This example adds a logging interceptor for commands. ```java @Configuration public class MessagingConfig { @Autowired private LoggingDispatchInterceptor loggingDispatchInterceptor; @Bean public MessagingConfigurer messagingConfigurer() { return configurer -> configurer.registerDispatchInterceptor(loggingDispatchInterceptor); } } ``` -------------------------------- ### Entity-Centric Stateful Handler Example Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Demonstrates an entity-centric approach to stateful command handlers where handlers are placed directly on the entity class. ```java @EventSourcedEntity public class MyEntity { @CommandHandler public void handle(MyCommand command, EventAppender appender) { // Handle the command and append events } } ``` -------------------------------- ### Axon Server Configuration with MessagingConfigurer Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Example of configuring Axon Server integration using the MessagingConfigurer, which is the recommended approach in Axon 5. ```java MessagingConfigurer.create(axonServerConfiguration).registerEventProcessorFactory(new PooledStreamingEventProcessorFactory()); ``` -------------------------------- ### Axon Framework 5: Given Phase Examples Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/test-fixtures.adoc Illustrates setting up the initial state for testing in Axon Framework 5 using the fluent API with events and commands. ```java fixture.given() .event(new CardIssuedEvent("card-1", 100)); ``` ```java fixture.given() .command(new IssueCardCommand("card-1", 100)); ``` ```java fixture.given() .noPriorActivity(); ``` -------------------------------- ### Get Event Message Timestamp Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/messaging-concepts/pages/anatomy-message.adoc Retrieve the timestamp indicating when an EventMessage occurred. No specific setup is required beyond having an EventMessage instance. ```java EventMessage event = // ... Instant occurredAt = event.timestamp(); ``` -------------------------------- ### Publish Event with Event Gateway Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/events/pages/event-publishing.adoc Use the EventGateway to publish events from components that are not entities. This example shows a basic setup for publishing a CardIssuedEvent. ```java import org.axonframework.messaging.eventhandling.gateway.EventGateway; import java.util.List; import java.util.concurrent.CompletableFuture; class Notifier { private EventGateway eventGateway; public CompletableFuture publishEvent() { return eventGateway.publish(List.of(new CardIssuedEvent("card-1", 100, "Axoniq shop"))); } } ``` -------------------------------- ### Axon Framework 4: Given Phase Examples Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/test-fixtures.adoc Demonstrates different ways to set up the initial state for testing in Axon Framework 4 using the 'given' method with events and commands. ```java fixture.given() .events(List.of(new CardIssuedEvent("card-1", 100), new CardRedeemedEvent("card-1", 20))); ``` ```java fixture.given() .command(new IssueCardCommand("card-1", 100)); ``` ```java fixture.given() .noPriorActivity(); ``` -------------------------------- ### Declarative Sequencing Policy Configuration Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/events/pages/event-processors/streaming.adoc Example of declarative configuration for a sequencing policy using EventProcessingConfigurer. This snippet shows the import statement for MessageStream, which is part of the configuration setup. ```java import org.axonframework.messaging.core.MessageStream; ``` -------------------------------- ### Axon Framework 5 Given Phase Examples Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/test-fixtures.adoc Shows how to set up prior state in Axon Framework 5's `AxonTestFixture` using single events, multiple events, or events as a list. Requires an `ApplicationConfigurer` to be set up. ```java import org.axonframework.common.configuration.ApplicationConfigurer; import org.axonframework.test.fixture.AxonTestFixture; import org.junit.jupiter.api.*; import java.util.List; class GiftCardTest { private AxonTestFixture fixture; @BeforeEach void setUp() { ApplicationConfigurer configurer = AxonConfig.appConfigurer(); fixture = AxonTestFixture.with(configurer); } @Test void givenSingleEvent() { fixture.given() .event(new CardIssuedEvent("card-1", 100)); // when... } @Test void givenMultipleEvents() { fixture.given() .events(new CardIssuedEvent("card-1", 100), new CardRedeemedEvent("card-1", 20)); // when... } @Test void givenEventsAsList() { fixture.given() ``` -------------------------------- ### Execute Create Course Command Source: https://github.com/axoniq/axonframework/blob/main/docs/getting-started/modules/ROOT/pages/implement-command-create-course.adoc Demonstrates starting the application configuration, creating a command, retrieving the CommandGateway, and sending the command to be processed. This is how you send commands in a running application. ```java public class UniversityAxonApplication { public static ApplicationConfigurer configurer() { return configurer(CreateCourseConfiguration::configure); } // This additional method allows us to selective register modules (helpful in tests) public static ApplicationConfigurer configurer(UnaryOperator customization) { var configurer = EventSourcingConfigurer.create(); configurer = customization.apply(configurer); return configurer; } public static void main(String[] args) { var configuration = configurer().start(); // <1> var createCourse = new CreateCourse(CourseId.random(), "Event Sourcing in Practice", 3); var commandGateway = configuration.getComponent(CommandGateway.class); // <2> commandGateway.sendAndWait(createCourse); // <3> } } ``` -------------------------------- ### Register Component with Lifecycle Handlers in Axon Framework 5 Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/configuration.adoc Axon Framework 5 integrates lifecycle handler registration into component registration via the ComponentRegistry. This example shows how to register a component with associated start and shutdown handlers. ```java import org.axonframework.common.configuration.ComponentDefinition; import org.axonframework.common.lifecycle.Phase; import org.axonframework.eventsourcing.configuration.EventSourcingConfigurer; class AxonApp { public static void main(String[] args) { EventSourcingConfigurer configurer = EventSourcingConfigurer.create(); configurer.componentRegistry(cr -> cr.registerComponent( ComponentDefinition.ofType(MyComponent.class) .withBuilder(config -> new MyComponent()) .onStart(Phase.LOCAL_MESSAGE_HANDLER_REGISTRATIONS, config -> {}) .onShutdown(Phase.LOCAL_MESSAGE_HANDLER_REGISTRATIONS, config -> {}) )); } } ``` -------------------------------- ### Given-Phase: Setting up a Single Event Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/testing/pages/basic-testing.adoc Sets up the initial state of a test by providing a single event. This is the recommended approach for granular control over the test's starting conditions. ```java import org.axonframework.test.fixture.AxonTestFixture; import org.junit.jupiter.api.*; class AccountTest { private AxonTestFixture fixture; @Test void test() { fixture.given() .event(new AccountCreatedEvent("account-1", 500.00)) .event(new MoneyDepositedEvent("account-1", 100.00)); // when... ``` -------------------------------- ### Command Logging Dispatch Interceptor Example Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/messaging-concepts/pages/message-intercepting.adoc An example implementation of a dispatch interceptor for CommandMessages that logs each command. ```APIDOC ## Command Logging Dispatch Interceptor Example ### Description This example shows how to create a dispatch interceptor that logs each command dispatched on a command bus. It implements the `MessageDispatchInterceptor` interface for `CommandMessage`. ### Method `interceptOnDispatch` ### Endpoint N/A (Implementation of an interface) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java public class CommandLoggingDispatchInterceptor implements MessageDispatchInterceptor { private static final Logger logger = LoggerFactory.getLogger(CommandLoggingDispatchInterceptor.class); @Override public MessageStream interceptOnDispatch( ``` -------------------------------- ### Axon 4 DispatchInterceptor Example Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/interceptors.adoc Example of a MessageDispatchInterceptor in Axon Framework 4, which handles message enrichment synchronously. ```java public class MyDispatchInterceptor implements MessageDispatchInterceptor> { @Override public BiFunction, CommandMessage> handle( List> messages) { return (index, message) -> { // Modify or enrich message return message.andMetaData(Collections.singletonMap("dispatchTime", Instant.now())); }; } } ``` -------------------------------- ### Custom Phases Example Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Demonstrates how to define and integrate custom processing phases into the lifecycle. This allows for extending the standard processing flow with application-specific steps. ```java @Configuration public class CustomPhaseConfig { @Bean public PhaseInterceptor customPhaseInterceptor() { return new CustomPhaseInterceptor(Phase.INVOCATION.value() + 5000); } } ``` -------------------------------- ### Configure Pooled Streaming Processors with Defaults and Overrides Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/events/pages/event-processors/streaming.adoc This Java example demonstrates setting default configurations for all Pooled Streaming Processors and then overriding specific settings for 'example-processor'. Defaults include event source, segment count, batch size, and claim extension threshold. The 'example-processor' overrides the segment count. ```java import org.axonframework.messaging.core.configuration.MessagingConfigurer; import org.axonframework.messaging.eventhandling.configuration.EventHandlingComponentsConfigurer; import org.axonframework.messaging.eventhandling.processing.streaming.pooled.PooledStreamingEventProcessorsConfigurer; import org.axonframework.messaging.eventstreaming.StreamableEventSource; import java.time.Duration; public class AxonConfig { public void configureEventProcessing(MessagingConfigurer configurer) { configurer.eventProcessing(eventConfigurer -> eventConfigurer.pooledStreaming( this::configurePooledStreamingProcessor )); } private PooledStreamingEventProcessorsConfigurer configurePooledStreamingProcessor( PooledStreamingEventProcessorsConfigurer pooledStreamingConfigurer ) { return pooledStreamingConfigurer // Set defaults for all pooled streaming processors .defaults((config, processorConfig) -> processorConfig .eventSource(config.getComponent(StreamableEventSource.class)) .segmentCount(4) .batchSize(100) .claimExtensionThreshold(Duration.ofSeconds(5)) ) // Configure a specific processor .processor( "example-processor", config -> config.eventHandlingComponents(this::configureHandlingComponent) .customize((c, pooledStreamingConfig) -> pooledStreamingConfig .segmentCount(8) // Override default for this processor ) ); } private EventHandlingComponentsConfigurer.AdditionalComponentPhase configureHandlingComponent( EventHandlingComponentsConfigurer.RequiredComponentPhase componentConfigurer ) { return componentConfigurer.autodetected(c -> new AnnotatedEventHandlingClass()); } } ``` -------------------------------- ### Axon 4 HandlerInterceptor Example Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/interceptors.adoc Example of a MessageHandlerInterceptor in Axon Framework 4, utilizing ThreadLocal-based UnitOfWork and synchronous processing. ```java public class MyHandlerInterceptor implements MessageHandlerInterceptor> { @Override public Object handle(UnitOfWork> unitOfWork, InterceptorChain interceptorChain) throws Exception { // Pre-processing unitOfWork.onCommit(uow -> { // Post-commit logic }); // Continue chain synchronously return interceptorChain.proceed(); } } ``` -------------------------------- ### Query Handler Example Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/queries/pages/query-dispatchers.adoc This is an example of a query handler that provides the initial state for a query. It uses JPA NamedQuery to fetch data. ```java @QueryHandler public List handle(FetchCardSummariesQuery query) { return entityManager .createNamedQuery("CardSummary.fetch", CardSummary.class) .setParameter("idStartsWith", query.getFilter().getIdStartsWith()) .setFirstResult(query.getOffset()) .setMaxResults(query.getLimit()) .getResultList(); } ``` -------------------------------- ### Given-Phase: Setting up a Single Event with Metadata Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/testing/pages/basic-testing.adoc Sets up the initial state of a test by providing a single event along with its associated metadata. This allows for testing event-driven logic that relies on contextual information. ```java import org.axonframework.messaging.core.Metadata; import org.axonframework.test.fixture.AxonTestFixture; import org.junit.jupiter.api.*; class AccountTest { private AxonTestFixture fixture; @Test void test() { fixture.given() .event(new AccountCreatedEvent("account-1", 500.00), Metadata.with("userId", "user-123")); // when... ``` -------------------------------- ### Axon Framework 4 Given Phase Examples Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/test-fixtures.adoc Demonstrates various ways to set up prior state in Axon Framework 4's `AggregateTestFixture` using single events, multiple events, events as a list, commands, or no prior activity. ```java import org.axonframework.test.aggregate.AggregateTestFixture; import org.axonframework.test.aggregate.FixtureConfiguration; import org.junit.jupiter.api.*; import java.util.List; class GiftCardTest { private FixtureConfiguration fixture; @BeforeEach void setUp() { fixture = new AggregateTestFixture<>(GiftCard.class); } @Test void givenSingleEvent() { fixture.given(new CardIssuedEvent("card-1", 100)); // when... } @Test void givenMultipleEvents() { fixture.given(new CardIssuedEvent("card-1", 100), new CardRedeemedEvent("card-1", 20)); // when... } @Test void givenEventsAsList() { fixture.given(List.of(new CardIssuedEvent("card-1", 100), new CardRedeemedEvent("card-1", 20))); // when... } @Test void givenCommands() { fixture.givenCommands(new IssueCardCommand("card-1", 100)); // when... } @Test void givenNoPriorActivity() { fixture.givenNoPriorActivity(); // when... } } ``` -------------------------------- ### EnqueuePolicy Example with AF5 API Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Example of using the EnqueuePolicy with the Axon Framework 5 API. This policy determines when a message should be enqueued into the dead-letter queue. ```java EnqueuePolicy.errorOnly() ``` -------------------------------- ### Issuing a Subscription Query Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/queries/pages/query-dispatchers.adoc This demonstrates how to issue a subscription query to receive initial state and subsequent updates. It involves sending a command, creating the query, subscribing to the results, and managing the subscription lifecycle. ```java // <1> commandGateway.sendAndWait(new IssueCardCommand("gc1", amount)); // <2> FetchCardSummariesQuery query = new FetchCardSummariesQuery(offset, limit, filter); // <3> Publisher results = queryGateway.subscriptionQuery( query, CardSummary.class ); // <4> Disposable subscription = Flux.from(results) .subscribe( cardSummary -> System.out.println("Received: " + cardSummary), error -> System.err.println("Error: " + error), () -> System.out.println("Completed") ); // <5> commandGateway.sendAndWait(new RedeemCardCommand("gc1", amount)); // <6> // When done, cancel the subscription subscription.dispose(); ``` -------------------------------- ### Client-Side Subscription Query with Reactor Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/queries/pages/infrastructure.adoc Demonstrates subscribing to a query using Reactor's Flux. This example shows how to initiate a subscription query, process incoming updates, handle completion and errors, and later cancel the subscription. ```java import org.axonframework.messaging.queryhandling.gateway.QueryGateway; import org.reactivestreams.Publisher; import reactor.core.Disposable; import reactor.core.publisher.Flux; public class QueryDispatcher { public void dispatchFetchCard(QueryGateway queryGateway) { String cardId = "..."; // Client-side subscription query Publisher results = queryGateway.subscriptionQuery( new FetchCardSummaryQuery(cardId), CardSummary.class ); // Subscribe using Reactor (requires reactor-core dependency) Disposable subscription = Flux.from(results) .doOnNext(summary -> System.out.println("Received: " + summary)) .doOnComplete(() -> System.out.println("No more updates")) .doOnError(error -> System.err.println("Error: " + error)) .subscribe(); // Later: cancel the subscription subscription.dispose(); } } ``` -------------------------------- ### Axon 5 HandlerInterceptor Example Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/interceptors.adoc Example of a MessageHandlerInterceptor in Axon Framework 5, showcasing async-first processing with MessageStream and explicit ProcessingContext, including lifecycle hooks. ```java public class MyHandlerInterceptor implements MessageHandlerInterceptor { @Override public MessageStream interceptOnHandle(CommandMessage message, ProcessingContext context, MessageHandlerInterceptorChain chain) { // Pre-processing context.runOnAfterCommit(ctx -> { // Post-commit logic }); // Continue chain - returns MessageStream return chain.proceed(message, context); } } ``` -------------------------------- ### Command Logging Dispatch Interceptor Example Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/messaging-concepts/pages/message-intercepting.adoc An example of a command dispatch interceptor that logs each command before it is dispatched on the command bus. It implements the MessageDispatchInterceptor interface for CommandMessage. ```java public class CommandLoggingDispatchInterceptor implements MessageDispatchInterceptor { private static final Logger logger = LoggerFactory.getLogger(CommandLoggingDispatchInterceptor.class); @Override public MessageStream interceptOnDispatch( ``` -------------------------------- ### Given-Phase: Setting up Multiple Events at Once Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/testing/pages/basic-testing.adoc Sets up the initial state of a test by providing multiple events simultaneously. This is useful for scenarios where several events have occurred in sequence before the action being tested. ```java import org.axonframework.test.fixture.AxonTestFixture; import org.junit.jupiter.api.*; class AccountTest { private AxonTestFixture fixture; @Test void test() { fixture.given() .events( new AccountCreatedEvent("account-1", 500.00), new MoneyDepositedEvent("account-1", 100.00) ); // when... ``` -------------------------------- ### Configuration API Example Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Configure Axon Query components using the MessagingConfigurer API. This provides a programmatic way to set up query buses, gateways, and interceptors. ```java @Bean public MessagingConfigurer messagingConfigurer() { return configurer -> { configurer.registerQueryBus( (config) -> AxonServerQueryBus.builder().build() ); configurer.registerQueryGateway( (config) -> DefaultQueryGateway.builder().build() ); }; } ``` -------------------------------- ### TransformingEventConverter Example Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Provides a practical workaround for event transformation by wrapping an EventConverter. This example demonstrates converting to a JsonNode intermediate representation and includes logic for adding and renaming fields. ```java public class TransformingEventConverter implements EventConverter { private final EventConverter delegate; public TransformingEventConverter(EventConverter delegate) { this.delegate = delegate; } @Override public Object convertPayload(EventMessage event) { // Check message type and version if (event.type().qualifiedName().name().equals("OrderPlaced") && event.type().version().equals("1.0")) { OrderPlacedEvent originalPayload = (OrderPlacedEvent) event.getPayload(); // Transformation logic: add computed fields EnrichedOrderPlacedEvent enrichedPayload = new EnrichedOrderPlacedEvent( originalPayload.getOrderId(), originalPayload.getProductId(), originalPayload.getQuantity(), originalPayload.getPrice() * originalPayload.getQuantity() // computed total price ); return enrichedPayload; } return delegate.convertPayload(event); } @Override public EventMessage convertEvent(EventMessage event) { return delegate.convertEvent(event); } } ``` -------------------------------- ### Axon Test Fixture Setup Source: https://github.com/axoniq/axonframework/blob/main/docs/getting-started/modules/ROOT/pages/implement-command-subscribe-student.adoc Sets up the Axon Test Fixture for testing the Subscribe Student functionality. Requires configuring the application slice. ```java class SubscribeStudentToCourseTest { private AxonTestFixture fixture; @BeforeEach void beforeEach() { var application = new UniversityAxonApplication(); var sliceConfigurer = application.configurer(SubscribeStudentConfiguration::configure); fixture = AxonTestFixture.with(sliceConfigurer); } @AfterEach void afterEach() { fixture.stop(); } @Test void successfulSubscription() { var courseId = CourseId.random(); var studentId = StudentId.random(); fixture.given() .event(new StudentEnrolledInFaculty(studentId, "Mateusz", "Nowak")) .event(new CourseCreated(courseId, "Axon Framework 5: Be a PRO", 2)) .when() .command(new SubscribeStudentToCourse(studentId, courseId)) .then() .events(new StudentSubscribedToCourse(studentId, courseId)); } @Test void studentAlreadySubscribed() { var courseId = CourseId.random(); ``` -------------------------------- ### Javadoc Example Template Source: https://github.com/axoniq/axonframework/blob/main/CLAUDE.md A template for Javadoc comments, including sections for purpose, architectural role, framework integration, and a usage example. Remember to include @author and @since tags. ```java /** * Brief description of component purpose and main responsibility. *

* Detailed explanation of architectural role and how it fits in the framework. * Main purpose is to [explain key benefit/capability]. *

* [Framework integration notes - who creates it, how to access it] *

* Example usage: *

{@code
 * // Realistic example using proper framework APIs
 * }
* * @author [Author Name] * @since [version, like 5.1.0] */ ``` -------------------------------- ### Configure Create Course Command Handling Source: https://github.com/axoniq/axonframework/blob/main/docs/getting-started/modules/ROOT/pages/implement-command-create-course.adoc Sets up an EventSourcingConfigurer to register an entity and a command handling module for creating courses. Use this to define your command handling components. ```java public class CreateCourseConfiguration { public static EventSourcingConfigurer configure(EventSourcingConfigurer configurer) { var stateEntity = EventSourcedEntityModule .autodetected(CourseId.class, CreateCourseCommandHandler.State.class); // <1> var commandHandlingModule = CommandHandlingModule .named("CreateCourse") .commandHandlers() .annotatedCommandHandlingComponent(c -> new CreateCourseCommandHandler()); return configurer .registerEntity(stateEntity) // <2> .registerCommandHandlingModule(commandHandlingModule); } } ``` -------------------------------- ### Implement Custom Routing Strategy Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/commands/pages/command-dispatchers.adoc Implement your own `RoutingStrategy` for completely custom routing logic. This example creates a composite routing key from multiple properties of a command payload. ```java public class CustomRoutingStrategy implements RoutingStrategy { @Override public String getRoutingKey(CommandMessage command) { // Custom logic to determine routing key MyCommand payload = command.payload(); return payload.tenantId() + ":" + payload.entityId(); // <1> } } ``` -------------------------------- ### Stateless Command Handler Example Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Illustrates a basic stateless command handler. This handler does not maintain state within itself but may access state through services. ```java public class MyCommandHandler { @CommandHandler public void handle(MyCommand command, EventAppender appender) { // Handle the command, potentially appending events using the appender } } ``` -------------------------------- ### ApplicationConfigurer Configuration Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Shows programmatic configuration using ApplicationConfigurer, demonstrating how to set up Axon components. ```java ApplicationConfigurer configurer = ApplicationConfigurer.defaultConfiguration(); configurer.registerModule(new EventSourcingModule()); configurer.registerModule(new MessagingModule()); // Further configuration... ApplicationContext context = configurer.buildApplicationContext(); ``` -------------------------------- ### Example Warning Message for Long Processing Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/messaging-concepts/pages/timeouts.adoc This text example illustrates the format of a warning message logged when a message handler is taking too long to process. It includes handler name, processing time, time remaining, and stack trace. ```text 2025-02-12T20:01:20.795Z WARN 68040 --- [playground-correlation] [ axon-janitor-0] axon-janitor : Message [io.axoniq.playground.publisher.MyContinuousEvent] for handler [io.axoniq.playground.publisher.PersistentStreamEventProcessor] is taking a long time to process. Current time: [5000ms]. Will be interrupted in [5000ms]. Stacktrace of current thread: java.base/java.lang.Thread.sleep0(Native Method) java.base/java.lang.Thread.sleep(Thread.java:509) io.axoniq.playground.publisher.PersistentStreamEventProcessor.handle(PersistentStreamEventProcessor.kt:16) java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) /** Removed some part of the stack trace for brevity **/ org.axonframework.messaging.timeout.TimeoutWrappedMessageHandlingMember.handle(TimeoutWrappedMessageHandlingMember.java:61) ``` -------------------------------- ### PostgreSQL Sequence Migration for Global Index Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/event-store.adoc This PostgreSQL SQL snippet creates a new sequence for the global index, ensuring it starts from the last value of the old sequence to prevent event ordering issues. It's crucial not to start from 1. An alternative is to rename the existing sequence if it's not used elsewhere. ```sql -- Migrate the global index sequence generator -- IMPORTANT: Do NOT create a new sequence starting from 1, as this will mess up event ordering! -- The old sequence name depends on your Hibernate/database configuration. -- Common names: 'hibernate_sequence', 'domain_event_entry_seq', or 'domain_event_entry_globalindex_seq' -- PostgreSQL example - create a new sequence starting from the current position of the old sequence: CREATE SEQUENCE aggregate_event_global_index_sequence START WITH (SELECT last_value + 1 FROM hibernate_sequence) INCREMENT BY 1; -- Alternatively, if you are 100% certain that 'hibernate_sequence' is NOT used by any other tables -- in your database, you can rename and adjust it directly instead: -- ALTER SEQUENCE hibernate_sequence RENAME TO aggregate_event_global_index_sequence; -- ALTER SEQUENCE aggregate_event_global_index_sequence INCREMENT BY 1; ``` -------------------------------- ### Configure Create Course Command Handling Module Source: https://github.com/axoniq/axonframework/blob/main/docs/getting-started/modules/ROOT/pages/implement-command-create-course.adoc This class configures the command handling module for creating courses. It registers the `CreateCourseCommandHandler` with Axon Framework. Use this when setting up the infrastructure for a specific command. ```java package io.axoniq.demo.university.faculty.write.createcourse; public class CreateCourseConfiguration { public static EventSourcingConfigurer configure(EventSourcingConfigurer configurer) { var commandHandlingModule = CommandHandlingModule.named("CreateCourse") // <1> .commandHandlers() .annotatedCommandHandlingComponent(c -> new CreateCourseCommandHandler()); // <2> return configurer.registerCommandHandlingModule(commandHandlingModule); // <3> } } ``` -------------------------------- ### ModellingConfigurer Configuration Source: https://github.com/axoniq/axonframework/blob/main/docs/changes-to-process.md Example of configuring Axon's modeling capabilities programmatically using ModellingConfigurer. ```java ApplicationConfigurer configurer = ApplicationConfigurer.defaultConfiguration(); configurer.registerModule(new ModellingConfigurer() { @Override public void register(Configuration config) { config.getComponent(AggregateConfigurer.class) .registerAggregate(MyEntity.class); } }); // Build context... ``` -------------------------------- ### Build Axon Configuration with Interceptors Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/commands/pages/configuration.adoc Demonstrates building a complex Axon configuration using the builder pattern, including registering entities, command handlers, and a command handler interceptor. ```java import org.axonframework.eventsourcing.configuration.EventSourcingConfigurer; import org.axonframework.messaging.commandhandling.configuration.CommandHandlingModule; public class AxonConfig { public AxonConfiguration buildConfiguration() { return EventSourcingConfigurer.create() // Register entities .registerEntity(EventSourcedEntityModule.autodetected( String.class, GiftCard.class) ) // Register command handlers .registerCommandHandlingModule( CommandHandlingModule.named("gift-card-commands").commandHandlers( handlers -> handlers.annotatedCommandHandlingComponent( config -> new GiftCardCommandHandler( config.getComponent(Repository.class) ) ) ) ) // Register interceptors .messaging(messagingConfigurer -> messagingConfigurer.registerCommandHandlerInterceptor( config -> (command, context, chain) -> { logger.info("Handling: {}", command.type().name()); return chain.proceed(command, context); } )) // Build and start .start(); } } ``` -------------------------------- ### Implement Custom EntityManagerProvider Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/events/pages/infrastructure.adoc Example implementation of a custom EntityManagerProvider for the AggregateBasedJpaEventStorageEngine. This allows for application-managed persistence contexts. ```java import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import org.axonframework.common.jpa.EntityManagerProvider; public class MyEntityManagerProvider implements EntityManagerProvider { private EntityManager entityManager; @Override public EntityManager getEntityManager() { return entityManager; } ``` -------------------------------- ### Order Creation Handler Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/commands/pages/infrastructure.adoc A simple handler for creating an Order aggregate. This is a basic example of a command handler. ```java public static Order handle(CreateOrderCommand command) { // Creation handler return new Order(command.orderId(), command.productId()); } } ``` -------------------------------- ### Create Basic AxonTestFixture Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/testing/pages/basic-testing.adoc Set up a basic AxonTestFixture by configuring EventSourcingConfigurer and registering entities. Ensure to stop the fixture in the @AfterEach method. ```java import org.axonframework.eventsourcing.configuration.EventSourcedEntityModule; import org.axonframework.eventsourcing.configuration.EventSourcingConfigurer; import org.axonframework.test.fixture.AxonTestFixture; import org.junit.jupiter.api.*; class AccountTest { private AxonTestFixture fixture; @BeforeEach void setUp() { EventSourcingConfigurer configurer = EventSourcingConfigurer.create() .registerEntity(EventSourcedEntityModule.autodetected( String.class, Account.class )); fixture = AxonTestFixture.with(configurer); } @AfterEach void tearDown() { fixture.stop(); // Always stop the fixture } // tests... } ``` -------------------------------- ### Default Jackson Serializer Configuration Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/serializers.adoc Configures the default Jackson serializer. This is a common setup for JSON serialization. ```java public Serializer serializer() { return JacksonSerializer.defaultSerializer(); } ``` -------------------------------- ### Using Repository in Command Handler Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/commands/pages/infrastructure.adoc Demonstrates loading an entity using a Repository within a command handler. The entity's state is then modified and events are appended. ```java @Component public class OrderCommandHandler { private final Repository orderRepository; public OrderCommandHandler(Repository orderRepository) { this.orderRepository = orderRepository; } @CommandHandler public void handle(ShipOrderCommand command, ProcessingContext context, EventAppender eventAppender) { // Load the entity orderRepository.load(command.orderId(), context) .thenAccept(managedOrder -> { Order order = managedOrder.entity(); // Apply business logic if (order.canShip()) { eventAppender.append(new OrderShippedEvent(command.orderId())); } }); } } ``` -------------------------------- ### Configure MyService Bean Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/configuration.adoc Example of configuring a MyService bean using a lambda expression within a configuration class. ```java ); } } ``` -------------------------------- ### Registering a Generic Message Handler Interceptor Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/messaging-concepts/pages/message-intercepting.adoc Example of how to register a generic message handler interceptor with Axon Framework. ```APIDOC ## Registering a Generic Message Handler Interceptor ### Description This example demonstrates how to register a generic `Message` interceptor with Axon, which will be applied to all message-specific dispatching or handling components. The `LoggingInterceptor` is provided by Axon out of the box. ### Method `registerMessageHandlerInterceptor` ### Endpoint N/A (Configuration method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java public void registerMessageHandlerInterceptor(MessagingConfigurer configurer) { configurer.registerMessageHandlerInterceptor( // The LoggingInterceptor is provided by Axon out of the box. config -> new LoggingInterceptor<>() ); } ``` ### Response #### Success Response (200) N/A (Configuration method) #### Response Example None ``` -------------------------------- ### Retrieve Message Payload in Java Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/messaging-concepts/pages/anatomy-message.adoc Demonstrates how to get the message payload as-is, converted to a specific type, or just its type. ```java public void retrievePayload(Message message) { // Get the payload as-is Object payload = message.payload(); // Get the payload converted to a specific type OrderPlacedEvent event = message.payloadAs(OrderPlacedEvent.class); // Get the payload type Class type = message.payloadType(); } ``` -------------------------------- ### Define Creational and Instance Command Handlers in Java Source: https://github.com/axoniq/axonframework/blob/main/axon-5/api-changes.md Example demonstrating both a static creational command handler and an instance command handler within an entity class. The creational handler is responsible for entity creation and event publishing, while the instance handler manages commands after the entity is established. ```java public class MyEntity { private String id; @EntityCreator public MyEntity(MyEntityCreatedEvent event) { this.id = event.getId(); // Other initialization logic... } // Creational command handler @CommandHandler public static void create(CreateMyEntityCommand command, EventAppender appender) { appender.append(new MyEntityCreatedEvent(command.getId(), command.getName())); } // Instance command handler @CommandHandler public void handle(UpdateMyEntityCommand command, EventAppender appender) { appender.append(new MyEntityUpdatedEvent(id, command.getNewName())); // Other update logic... } } ``` -------------------------------- ### Axon Framework 5 Static Command Handler for Creation Source: https://github.com/axoniq/axonframework/blob/main/docs/reference-guide/modules/migration/pages/paths/aggregates/index.adoc Demonstrates the recommended approach for entity creation in Axon 5 using a static @CommandHandler, aligning with CreationPolicy.ALWAYS. ```java @CommandHandler public static void handle(IssueGiftCard cmd, EventAppender eventAppender) { eventAppender.append(new GiftCardIssued(cmd.cardId(), cmd.amount())); } ```