### Complete Phone Call Example Source: https://context7.com/stateless4j/stateless4j/llms.txt A comprehensive example demonstrating multiple features including substates, entry/exit actions, and transitions for a phone call simulation. ```java public class PhoneCallExample { enum State { OffHook, Ringing, Connected, OnHold, PhoneDestroyed } enum Trigger { CallDialed, HungUp, CallConnected, PlacedOnHold, TakenOffHold, LeftMessage, PhoneHurledAgainstWall } private StateMachine phoneCall; private long callStartTime; public PhoneCallExample() { StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.OffHook) .permit(Trigger.CallDialed, State.Ringing); config.configure(State.Ringing) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.CallConnected, State.Connected); config.configure(State.Connected) .onEntry(() -> callStartTime = System.currentTimeMillis()) .onExit(() -> { long duration = System.currentTimeMillis() - callStartTime; System.out.println("Call duration: " + duration + "ms"); }) .permit(Trigger.LeftMessage, State.OffHook) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.PlacedOnHold, State.OnHold); config.configure(State.OnHold) .substateOf(State.Connected) // OnHold is still Connected .permit(Trigger.TakenOffHold, State.Connected) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.PhoneHurledAgainstWall, State.PhoneDestroyed); phoneCall = new StateMachine<>(State.OffHook, config); } public void dial() { phoneCall.fire(Trigger.CallDialed); } public void connect() { phoneCall.fire(Trigger.CallConnected); } public void hold() { phoneCall.fire(Trigger.PlacedOnHold); } public void resume() { phoneCall.fire(Trigger.TakenOffHold); } public void hangUp() { phoneCall.fire(Trigger.HungUp); } public State getState() { return phoneCall.getState(); } public boolean isConnected() { return phoneCall.isInState(State.Connected); } public static void main(String[] args) throws InterruptedException { PhoneCallExample phone = new PhoneCallExample(); phone.dial(); System.out.println(phone.getState()); // Ringing phone.connect(); System.out.println(phone.getState()); // Connected System.out.println(phone.isConnected()); // true phone.hold(); System.out.println(phone.getState()); // OnHold System.out.println(phone.isConnected()); // true (substate of Connected) Thread.sleep(100); phone.hangUp(); // Outputs: Call duration: ~100ms System.out.println(phone.getState()); // OffHook } } ``` -------------------------------- ### fireInitialTransition() - Initial State Entry Actions Source: https://context7.com/stateless4j/stateless4j/llms.txt Fires an initial transition into the starting state, ensuring all entry actions, including superstate entry actions, are executed. ```APIDOC ## fireInitialTransition() ### Description Fire an initial transition into the starting state, executing all entry actions including superstate entry actions. Must be called before any other triggers. ### Method `fireInitialTransition` ### Endpoint `StateMachine.fireInitialTransition()` ### Parameters None ### Request Example ```java sm.fireInitialTransition(); // Explicitly enter initial state hierarchy // Output: // Entered Parent // Entered Child ``` ### Response N/A (This is an operation method) ``` -------------------------------- ### getPermittedTriggers() - Get Available Triggers Source: https://context7.com/stateless4j/stateless4j/llms.txt Retrieves a list of triggers that are currently valid and can be fired from the current state, considering guard conditions. ```APIDOC ## getPermittedTriggers() ### Description Get a list of triggers that are currently valid based on the current state and guard conditions. ### Method `getPermittedTriggers` ### Endpoint `StateMachine.getPermittedTriggers()` ### Parameters None ### Request Example ```java // Get available triggers List permitted = sm.getPermittedTriggers(); System.out.println(permitted); // [Submit, Delete, Publish] // Check specific trigger System.out.println(sm.canFire(Trigger.Submit)); // true System.out.println(sm.canFire(Trigger.Approve)); // false ``` ### Response #### Success Response (List) - **permittedTriggers** (List) - A list of triggers that can be fired from the current state. #### Response Example ```json ["Submit", "Delete", "Publish"] ``` ``` -------------------------------- ### Get Permitted Triggers in Java Source: https://context7.com/stateless4j/stateless4j/llms.txt Retrieve a list of triggers that can be fired from the current state, considering guard conditions. Useful for UI enablement or validation. ```java StateMachineConfig config = new StateMachineConfig<>(); boolean hasPermission = true; config.configure(State.Draft) .permit(Trigger.Submit, State.Review) .permit(Trigger.Delete, State.Deleted) .permitIf(Trigger.Publish, State.Published, () -> hasPermission); StateMachine sm = new StateMachine<>(State.Draft, config); // Get available triggers List permitted = sm.getPermittedTriggers(); System.out.println(permitted); // [Submit, Delete, Publish] // Check specific trigger System.out.println(sm.canFire(Trigger.Submit)); // true System.out.println(sm.canFire(Trigger.Approve)); // false hasPermission = false; permitted = sm.getPermittedTriggers(); System.out.println(permitted); // [Submit, Delete] - Publish not included ``` -------------------------------- ### Configure Simple and Action Transitions Source: https://context7.com/stateless4j/stateless4j/llms.txt Defines simple state transitions and transitions that execute an action during the transition. Requires StateMachineConfig. ```java StateMachineConfig config = new StateMachineConfig<>(); // Simple transition config.configure(State.A) .permit(Trigger.X, State.B); // Transition with action executed during transition config.configure(State.B) .permit(Trigger.Y, State.C, () -> { System.out.println("Transition action executed between exit and entry"); }); StateMachine sm = new StateMachine<>(State.A, config); sm.fire(Trigger.X); // Transitions A -> B sm.fire(Trigger.Y); // Transitions B -> C, action executes during transition ``` -------------------------------- ### Create StateMachine Instance Source: https://context7.com/stateless4j/stateless4j/llms.txt Instantiate a StateMachine with an initial state and an optional configuration. Supports external state storage for persistence. ```java // Simple constructor with just initial state (configuration added later) StateMachine sm = new StateMachine<>(State.A); sm.configure(State.A).permit(Trigger.X, State.B); sm.configure(State.B).permit(Trigger.Y, State.A); // Constructor with separate configuration (reusable across instances) StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.A).permit(Trigger.X, State.B); config.configure(State.B).permit(Trigger.Y, State.A); StateMachine sm1 = new StateMachine<>(State.A, config); StateMachine sm2 = new StateMachine<>(State.B, config); // Constructor with external state storage (for persistence scenarios) AtomicReference stateHolder = new AtomicReference<>(State.A); StateMachine sm3 = new StateMachine<>( State.A, () -> stateHolder.get(), // state accessor (s) -> stateHolder.set(s), // state mutator config ); ``` -------------------------------- ### Fire Initial State Transition in Java Source: https://context7.com/stateless4j/stateless4j/llms.txt Explicitly fire the initial transition to ensure all entry actions, including those in superstates, are executed upon state machine initialization. Must be called before other triggers. ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.Parent) .onEntry(() -> System.out.println("Entered Parent")); config.configure(State.Child) .substateOf(State.Parent) .onEntry(() -> System.out.println("Entered Child")) .permit(Trigger.Next, State.Other); StateMachine sm = new StateMachine<>(State.Child, config); // Without fireInitialTransition(), entry actions don't run on initialization sm.fire(Trigger.Next); // Only fires exit/entry for this transition // Reset and use fireInitialTransition sm = new StateMachine<>(State.Child, config); sm.fireInitialTransition(); // Explicitly enter initial state hierarchy // Output: // Entered Parent // Entered Child ``` -------------------------------- ### StateConfiguration.onEntry() and onExit() Source: https://context7.com/stateless4j/stateless4j/llms.txt Specifies actions to be executed automatically when a state is entered or exited. These actions can access details about the transition. ```APIDOC ## StateConfiguration.onEntry() and onExit() ### Description Specify actions to execute when entering or exiting a state. Actions can access transition details including source state, destination, and trigger. ### Method `onEntry(Action action)` `onEntry(TransitionAction action)` `onExit(Action action)` `onExit(TransitionAction action)` ### Endpoint N/A (This is a configuration method within the StateMachineConfig) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.A) .onEntry(() -> System.out.println("Entered state A")) .onExit(() -> System.out.println("Exiting state A")) .permit(Trigger.X, State.B); // Entry action with transition details config.configure(State.B) .onEntry(transition -> { System.out.println("Entered B from " + transition.getSource()); System.out.println("Triggered by " + transition.getTrigger()); System.out.println("Is reentry: " + transition.isReentry()); }) .onExit(transition -> { System.out.println("Leaving B, going to " + transition.getDestination()); }) .permit(Trigger.Y, State.C); ``` ### Response N/A (Configuration method, does not return a response) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### StateConfiguration.permit() Source: https://context7.com/stateless4j/stateless4j/llms.txt Defines a direct transition from one state to another upon receiving a specific trigger. An optional action can be executed during the transition. ```APIDOC ## StateConfiguration.permit() ### Description Accept a trigger and transition to a destination state. Optionally execute an action during the transition (after onExit, before onEntry). ### Method `permit(Trigger trigger, State destination, Action action)` `permit(Trigger trigger, State destination)` ### Endpoint N/A (This is a configuration method within the StateMachineConfig) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); // Simple transition config.configure(State.A) .permit(Trigger.X, State.B); // Transition with action executed during transition config.configure(State.B) .permit(Trigger.Y, State.C, () -> { System.out.println("Transition action executed between exit and entry"); }); ``` ### Response N/A (Configuration method, does not return a response) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Configure State Machine Transitions and Actions Source: https://context7.com/stateless4j/stateless4j/llms.txt Define states, triggers, and transitions using a fluent API. Supports entry/exit actions and conditional permits. Use enums for states and triggers for clarity. ```java // Define states and triggers as enums enum State { OffHook, Ringing, Connected, OnHold, PhoneDestroyed } enum Trigger { CallDialed, HungUp, CallConnected, PlacedOnHold, TakenOffHold, LeftMessage, PhoneHurledAgainstWall } // Create reusable configuration StateMachineConfig phoneCallConfig = new StateMachineConfig<>(); phoneCallConfig.configure(State.OffHook) .permit(Trigger.CallDialed, State.Ringing); phoneCallConfig.configure(State.Ringing) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.CallConnected, State.Connected); phoneCallConfig.configure(State.Connected) .onEntry(() -> System.out.println("Call timer started")) .onExit(() -> System.out.println("Call timer stopped")) .permit(Trigger.LeftMessage, State.OffHook) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.PlacedOnHold, State.OnHold); phoneCallConfig.configure(State.OnHold) .substateOf(State.Connected) .permit(Trigger.TakenOffHold, State.Connected) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.PhoneHurledAgainstWall, State.PhoneDestroyed); // Create state machine instance with initial state StateMachine phoneCall = new StateMachine<>(State.OffHook, phoneCallConfig); ``` -------------------------------- ### Configure Basic State Machine in Java Source: https://github.com/stateless4j/stateless4j/blob/master/README.md Define states and transitions for a phone call state machine using Java 8 method references. Ensure necessary enum types for State and Trigger are defined. ```java StateMachineConfig phoneCallConfig = new StateMachineConfig<>(); phoneCallConfig.configure(State.OffHook) .permit(Trigger.CallDialed, State.Ringing); phoneCallConfig.configure(State.Ringing) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.CallConnected, State.Connected); // this example uses Java 8 method references // a Java 7 example is provided in /examples phoneCallConfig.configure(State.Connected) .onEntry(this::startCallTimer) .onExit(this::stopCallTimer) .permit(Trigger.LeftMessage, State.OffHook) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.PlacedOnHold, State.OnHold); // ... StateMachine phoneCall = new StateMachine<>(State.OffHook, phoneCallConfig); phoneCall.fire(Trigger.CallDialed); assertEquals(State.Ringing, phoneCall.getState()); ``` -------------------------------- ### Configure State Entry and Exit Actions Source: https://context7.com/stateless4j/stateless4j/llms.txt Specifies actions to be executed when entering or exiting a state. Actions can access transition details. Requires StateMachineConfig. ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.A) .onEntry(() -> System.out.println("Entered state A")) .onExit(() -> System.out.println("Exiting state A")) .permit(Trigger.X, State.B); // Entry action with transition details config.configure(State.B) .onEntry(transition -> { System.out.println("Entered B from " + transition.getSource()); System.out.println("Triggered by " + transition.getTrigger()); System.out.println("Is reentry: " + transition.isReentry()); }) .onExit(transition -> { System.out.println("Leaving B, going to " + transition.getDestination()); }) .permit(Trigger.Y, State.C); StateMachine sm = new StateMachine<>(State.A, config); sm.fire(Trigger.X); // Output: // Exiting state A // Entered B from A // Triggered by X // Is reentry: false ``` -------------------------------- ### Configure Dynamic State Transitions in Java Source: https://context7.com/stateless4j/stateless4j/llms.txt Use permitDynamic to define state transitions where the destination state is determined at runtime based on conditions or trigger parameters. Requires StateMachineConfig. ```java StateMachineConfig config = new StateMachineConfig<>(); // Dynamic destination based on external condition boolean isPremiumUser = true; config.configure(State.Checkout) .permitDynamic(Trigger.Pay, () -> { return isPremiumUser ? State.PremiumProcessing : State.StandardProcessing; }); // Dynamic destination based on trigger parameter TriggerWithParameters1 assignTrigger = config.setTriggerParameters(Trigger.Assign, Integer.class); config.configure(State.Unassigned) .permitDynamic(assignTrigger, (priority) -> { if (priority >= 8) return State.HighPriority; if (priority >= 4) return State.MediumPriority; return State.LowPriority; }); StateMachine sm = new StateMachine<>(State.Unassigned, config); sm.fire(assignTrigger, 9); System.out.println(sm.getState()); // Output: HighPriority ``` -------------------------------- ### Fire Triggers to Transition States Source: https://context7.com/stateless4j/stateless4j/llms.txt Initiate state transitions by firing triggers. This executes exit actions, transition actions, and entry actions in order. ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.A).permit(Trigger.X, State.B); config.configure(State.B).permit(Trigger.Y, State.C); config.configure(State.C).permit(Trigger.Z, State.A); StateMachine sm = new StateMachine<>(State.A, config); // Fire triggers to transition between states System.out.println("Initial: " + sm.getState()); // Output: A sm.fire(Trigger.X); System.out.println("After X: " + sm.getState()); // Output: B sm.fire(Trigger.Y); System.out.println("After Y: " + sm.getState()); // Output: C sm.fire(Trigger.Z); System.out.println("After Z: " + sm.getState()); // Output: A ``` -------------------------------- ### Parameterized Triggers Source: https://context7.com/stateless4j/stateless4j/llms.txt Demonstrates how to define and use triggers that carry parameters. Parameters can be passed to entry actions, allowing for dynamic behavior based on trigger data. ```APIDOC ## Parameterized Triggers ### Description Pass parameters with triggers and access them in entry actions. Define parameter types using setTriggerParameters(). ### Method `setTriggerParameters(Trigger trigger, Class... classes)` ### Endpoint N/A (This is a library configuration method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); // Define trigger with parameters TriggerWithParameters1 loginTrigger = config.setTriggerParameters(Trigger.Login, String.class); TriggerWithParameters2 purchaseTrigger = config.setTriggerParameters(Trigger.Purchase, String.class, Integer.class); config.configure(State.LoggedOut) .permit(Trigger.Login, State.LoggedIn); config.configure(State.LoggedIn) // Access single parameter in entry action .onEntryFrom(loginTrigger, (username) -> { System.out.println("User logged in: " + username); }) .permit(Trigger.Purchase, State.Purchasing); config.configure(State.Purchasing) // Access multiple parameters .onEntryFrom(purchaseTrigger, (item, quantity) -> { System.out.println("Purchasing " + quantity + " of " + item); }) .permit(Trigger.Complete, State.LoggedIn); StateMachine sm = new StateMachine<>(State.LoggedOut, config); // Fire with parameters sm.fire(loginTrigger, "john_doe"); // Output: User logged in: john_doe sm.fire(purchaseTrigger, "Widget", 5); // Output: Purchasing 5 of Widget ``` ### Response #### Success Response (200) N/A (This is a configuration method, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Configure Conditional Transitions with Guards Source: https://context7.com/stateless4j/stateless4j/llms.txt Sets up state transitions that only occur if a specified guard condition evaluates to true. Useful for enforcing business rules. Requires StateMachineConfig. ```java StateMachineConfig config = new StateMachineConfig<>(); boolean isAuthorized = true; int retryCount = 0; config.configure(State.Pending) // Transition only allowed if authorized .permitIf(Trigger.Submit, State.Processing, () -> isAuthorized) // Multiple guards for same trigger - first matching wins .permitIf(Trigger.Retry, State.Pending, () -> retryCount < 3) .permitIf(Trigger.Retry, State.Failed, () -> retryCount >= 3); config.configure(State.Processing) .permit(Trigger.Complete, State.Done) .permit(Trigger.Fail, State.Failed); StateMachine sm = new StateMachine<>(State.Pending, config); // Check if trigger can fire before attempting if (sm.canFire(Trigger.Submit)) { sm.fire(Trigger.Submit); } ``` -------------------------------- ### Enable Runtime Tracing in Java Source: https://context7.com/stateless4j/stateless4j/llms.txt Enable runtime tracing to monitor trigger events and state transitions by providing a Trace implementation. Set to null to disable tracing. ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.A).permit(Trigger.X, State.B); config.configure(State.B).permit(Trigger.Y, State.A); StateMachine sm = new StateMachine<>(State.A, config); // Set trace delegate for debugging sm.setTrace(new Trace() { @Override public void trigger(Trigger trigger) { System.out.println("[TRACE] Trigger fired: " + trigger); } @Override public void transition(Trigger trigger, State source, State destination) { System.out.println("[TRACE] Transition: " + source + " -> " + destination + " via " + trigger); } }); sm.fire(Trigger.X); // Output: // [TRACE] Trigger fired: X // [TRACE] Transition: A -> B via X sm.fire(Trigger.Y); // Output: // [TRACE] Trigger fired: Y // [TRACE] Transition: B -> A via Y // Disable tracing sm.setTrace(null); ``` -------------------------------- ### StateConfiguration.permitInternal() Source: https://context7.com/stateless4j/stateless4j/llms.txt Allows an internal transition within a state. An action is executed, but state entry and exit actions are skipped, and the state itself does not change. ```APIDOC ## permitInternal() ### Description Execute an action without changing state or triggering entry/exit actions. Useful for handling events that should be processed but don't cause transitions. ### Method `permitInternal(Trigger trigger, Action action)` ### Endpoint N/A (This is a library configuration method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); int clickCount = 0; config.configure(State.Idle) .onEntry(() -> System.out.println("Entry action")) .onExit(() -> System.out.println("Exit action")) // Internal transition: action runs, but no entry/exit actions .permitInternal(Trigger.Click, () -> { clickCount++; System.out.println("Click handled, count: " + clickCount); }) .permit(Trigger.Submit, State.Processing); StateMachine sm = new StateMachine<>(State.Idle, config); sm.fire(Trigger.Click); // Output: Click handled, count: 1 sm.fire(Trigger.Click); // Output: Click handled, count: 2 // Note: No "Entry action" or "Exit action" printed - state doesn't change System.out.println(sm.getState()); // Output: Idle ``` ### Response #### Success Response (200) N/A (This is a configuration method, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### setTrace() - Enable Runtime Tracing Source: https://context7.com/stateless4j/stateless4j/llms.txt Enables runtime tracing to monitor trigger events and state transitions, useful for debugging and logging. ```APIDOC ## setTrace() ### Description Enable runtime tracing to monitor trigger events and state transitions for debugging or logging purposes. ### Method `setTrace` ### Endpoint `StateMachine.setTrace(Trace traceDelegate)` ### Parameters - **traceDelegate** (Trace) - An object implementing the Trace interface to handle trace events. Set to `null` to disable tracing. ### Request Example ```java // Set trace delegate for debugging sm.setTrace(new Trace() { @Override public void trigger(Trigger trigger) { System.out.println("[TRACE] Trigger fired: " + trigger); } @Override public void transition(Trigger trigger, State source, State destination) { System.out.println("[TRACE] Transition: " + source + " -> " + destination + " via " + trigger); } }); sm.fire(Trigger.X); // Output: // [TRACE] Trigger fired: X // [TRACE] Transition: A -> B via X // Disable tracing sm.setTrace(null); ``` ### Response N/A (This is a configuration method) ``` -------------------------------- ### StateConfiguration.permitIf() Source: https://context7.com/stateless4j/stateless4j/llms.txt Allows transitions only if a specified guard condition evaluates to true. This enables conditional state changes based on runtime logic. ```APIDOC ## StateConfiguration.permitIf() ### Description Accept a trigger and transition only if the guard condition returns true. Guards enable conditional transitions based on runtime state. ### Method `permitIf(Trigger trigger, State destination, Guard guard)` `permitIf(Trigger trigger, State destination, Action action, Guard guard)` ### Endpoint N/A (This is a configuration method within the StateMachineConfig) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); boolean isAuthorized = true; int retryCount = 0; config.configure(State.Pending) // Transition only allowed if authorized .permitIf(Trigger.Submit, State.Processing, () -> isAuthorized) // Multiple guards for same trigger - first matching wins .permitIf(Trigger.Retry, State.Pending, () -> retryCount < 3) .permitIf(Trigger.Retry, State.Failed, () -> retryCount >= 3); config.configure(State.Processing) .permit(Trigger.Complete, State.Done) .permit(Trigger.Fail, State.Failed); ``` ### Response N/A (Configuration method, does not return a response) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Generate Graphviz DOT File Source: https://context7.com/stateless4j/stateless4j/llms.txt Generates a Graphviz DOT file representation of the state machine. Use the overload with `printLabels = true` to include transition labels. ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.A) .permit(Trigger.X, State.B) .permit(Trigger.Y, State.C); config.configure(State.B) .permit(Trigger.Y, State.C); config.configure(State.C) .permit(Trigger.X, State.A); // Generate DOT file without labels ByteArrayOutputStream dotFile = new ByteArrayOutputStream(); config.generateDotFileInto(dotFile); System.out.println(dotFile.toString("UTF-8")); // Output: // digraph G { // A -> B; // A -> C; // B -> C; // C -> A; // } // Generate DOT file with transition labels dotFile = new ByteArrayOutputStream(); config.generateDotFileInto(dotFile, true); // printLabels = true System.out.println(dotFile.toString("UTF-8")); // Output: // digraph G { // A -> B [label = "X" ]; // A -> C [label = "Y" ]; // B -> C [label = "Y" ]; // C -> A [label = "X" ]; // } // Write to file try (FileOutputStream fos = new FileOutputStream("statemachine.dot")) { config.generateDotFileInto(fos, true); } // Then render with: dot -Tpng statemachine.dot -o statemachine.png ``` -------------------------------- ### Pass Parameters with Triggers Source: https://context7.com/stateless4j/stateless4j/llms.txt Define triggers with parameters using `setTriggerParameters` and access these parameters in entry actions. This allows passing data along with the trigger event. ```java StateMachineConfig config = new StateMachineConfig<>(); // Define trigger with parameters TriggerWithParameters1 loginTrigger = config.setTriggerParameters(Trigger.Login, String.class); TriggerWithParameters2 purchaseTrigger = config.setTriggerParameters(Trigger.Purchase, String.class, Integer.class); config.configure(State.LoggedOut) .permit(Trigger.Login, State.LoggedIn); config.configure(State.LoggedIn) // Access single parameter in entry action .onEntryFrom(loginTrigger, (username) -> { System.out.println("User logged in: " + username); }) .permit(Trigger.Purchase, State.Purchasing); config.configure(State.Purchasing) // Access multiple parameters .onEntryFrom(purchaseTrigger, (item, quantity) -> { System.out.println("Purchasing " + quantity + " of " + item); }) .permit(Trigger.Complete, State.LoggedIn); StateMachine sm = new StateMachine<>(State.LoggedOut, config); // Fire with parameters sm.fire(loginTrigger, "john_doe"); // Output: User logged in: john_doe sm.fire(purchaseTrigger, "Widget", 5); // Output: Purchasing 5 of Widget ``` -------------------------------- ### permitDynamic() - Dynamic State Transitions Source: https://context7.com/stateless4j/stateless4j/llms.txt Allows defining state transitions where the destination state is determined dynamically at runtime based on conditions or trigger parameters. ```APIDOC ## permitDynamic() ### Description Transition to a state calculated dynamically at runtime based on conditions or trigger parameters. ### Method `permitDynamic` ### Parameters - **trigger** (Trigger) - The trigger that initiates the transition. - **destinationSupplier** (Supplier or Function or Function) - A function that returns the destination state dynamically. ### Request Example ```java // Dynamic destination based on external condition boolean isPremiumUser = true; config.configure(State.Checkout) .permitDynamic(Trigger.Pay, () -> { return isPremiumUser ? State.PremiumProcessing : State.StandardProcessing; }); // Dynamic destination based on trigger parameter TriggerWithParameters1 assignTrigger = config.setTriggerParameters(Trigger.Assign, Integer.class); config.configure(State.Unassigned) .permitDynamic(assignTrigger, (priority) -> { if (priority >= 8) return State.HighPriority; if (priority >= 4) return State.MediumPriority; return State.LowPriority; }); ``` ### Response N/A (This is a configuration method) ``` -------------------------------- ### StateConfiguration.permitReentry() Source: https://context7.com/stateless4j/stateless4j/llms.txt Allows a state to transition back to itself. This process includes executing the state's exit actions followed by its entry actions, differentiating it from `permitInternal`. ```APIDOC ## permitReentry() ### Description Allow a state to transition to itself, executing exit and entry actions. Different from permitInternal which skips exit/entry actions. ### Method `permitReentry(Trigger trigger)` `permitReentry(Trigger trigger, Action action)` ### Endpoint N/A (This is a library configuration method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.Processing) .onEntry(() -> System.out.println("Processing started/restarted")) .onExit(() -> System.out.println("Processing interrupted")) .permitReentry(Trigger.Retry) // Self-transition with exit/entry .permitReentry(Trigger.Reset, () -> { System.out.println("Reset action during reentry"); }) .permit(Trigger.Complete, State.Done); StateMachine sm = new StateMachine<>(State.Processing, config); sm.fire(Trigger.Retry); // Output: // Processing interrupted (exit) // Processing started/restarted (entry) sm.fire(Trigger.Reset); // Output: // Processing interrupted (exit) // Reset action during reentry // Processing started/restarted (entry) ``` ### Response #### Success Response (200) N/A (This is a configuration method, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### StateConfiguration.substateOf() Source: https://context7.com/stateless4j/stateless4j/llms.txt Establishes a hierarchical relationship between states, allowing substates to inherit transitions and behaviors from their parent states. ```APIDOC ## StateConfiguration.substateOf() ### Description Define hierarchical states where a substate inherits transitions from its superstate. Entry/exit actions are executed for the entire hierarchy. ### Method `substateOf(State superstate)` ### Endpoint N/A (This is a configuration method within the StateMachineConfig) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); // Parent state with shared behavior config.configure(State.Connected) .onEntry(() -> System.out.println("Connection established")) .onExit(() -> System.out.println("Connection closed")) .permit(Trigger.Disconnect, State.Disconnected); // Substates inherit Disconnect transition from Connected config.configure(State.Streaming) .substateOf(State.Connected) .onEntry(() -> System.out.println("Streaming started")) .permit(Trigger.Pause, State.Paused); config.configure(State.Paused) .substateOf(State.Connected) .onEntry(() -> System.out.println("Streaming paused")) .permit(Trigger.Resume, State.Streaming); ``` ### Response N/A (Configuration method, does not return a response) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Configure Transitions that Ignore Conditions Source: https://context7.com/stateless4j/stateless4j/llms.txt Allows transitions to be ignored silently if a guard condition is false, preventing exceptions. Useful for optional or conditional actions. Requires StateMachineConfig. ```java StateMachineConfig config = new StateMachineConfig<>(); boolean canProceed = false; config.configure(State.Waiting) // If canProceed is false, trigger is ignored silently .permitIfElseIgnore(Trigger.Go, State.Running, () -> canProceed) .permit(Trigger.Cancel, State.Cancelled); StateMachine sm = new StateMachine<>(State.Waiting, config); // This won't throw an exception, just stays in Waiting state sm.fire(Trigger.Go); System.out.println(sm.getState()); // Output: Waiting canProceed = true; sm.fire(Trigger.Go); System.out.println(sm.getState()); // Output: Running ``` -------------------------------- ### Allow State Reentry with permitReentry Source: https://context7.com/stateless4j/stateless4j/llms.txt Use `permitReentry` to allow a state to transition to itself, executing exit and entry actions. This differs from `permitInternal` as it includes the exit and entry actions. ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.Processing) .onEntry(() -> System.out.println("Processing started/restarted")) .onExit(() -> System.out.println("Processing interrupted")) .permitReentry(Trigger.Retry) // Self-transition with exit/entry .permitReentry(Trigger.Reset, () -> { System.out.println("Reset action during reentry"); }) .permit(Trigger.Complete, State.Done); StateMachine sm = new StateMachine<>(State.Processing, config); sm.fire(Trigger.Retry); // Output: // Processing interrupted (exit) // Processing started/restarted (entry) sm.fire(Trigger.Reset); // Output: // Processing interrupted (exit) // Reset action during reentry // Processing started/restarted (entry) ``` -------------------------------- ### Define Hierarchical State in Java Source: https://github.com/stateless4j/stateless4j/blob/master/README.md Configure a substate within a parent state. The `isInState` method correctly accounts for substates. ```java phoneCall.configure(State.OnHold) .substateOf(State.Connected) .permit(Trigger.TakenOffHold, State.Connected) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.PhoneHurledAgainstWall, State.PhoneDestroyed); ``` -------------------------------- ### Define Hierarchical States with Substates Source: https://context7.com/stateless4j/stateless4j/llms.txt Establishes parent-child state relationships where substates inherit transitions from their superstates. Entry/exit actions propagate through the hierarchy. Requires StateMachineConfig. ```java StateMachineConfig config = new StateMachineConfig<>(); // Parent state with shared behavior config.configure(State.Connected) .onEntry(() -> System.out.println("Connection established")) .onExit(() -> System.out.println("Connection closed")) .permit(Trigger.Disconnect, State.Disconnected); // Substates inherit Disconnect transition from Connected config.configure(State.Streaming) .substateOf(State.Connected) .onEntry(() -> System.out.println("Streaming started")) .permit(Trigger.Pause, State.Paused); config.configure(State.Paused) .substateOf(State.Connected) .onEntry(() -> System.out.println("Streaming paused")) .permit(Trigger.Resume, State.Streaming); StateMachine sm = new StateMachine<>(State.Streaming, config); // isInState checks superstate hierarchy System.out.println(sm.isInState(State.Streaming)); // true System.out.println(sm.isInState(State.Connected)); // true (superstate) // Substate can use parent's transition sm.fire(Trigger.Disconnect); // Works - inherited from Connected // Output: // Connection closed (exit from Connected hierarchy) ``` -------------------------------- ### StateConfiguration.ignore() Source: https://context7.com/stateless4j/stateless4j/llms.txt Configures the state machine to ignore a specific trigger when the machine is in a particular state. This prevents exceptions from being thrown for unexpected triggers. ```APIDOC ## ignore() ### Description Ignore a trigger when in a specific state without throwing an exception. ### Method `ignore(Trigger trigger)` ### Endpoint N/A (This is a library configuration method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.Locked) .ignore(Trigger.Lock) // Already locked, ignore lock requests .permit(Trigger.Unlock, State.Unlocked); config.configure(State.Unlocked) .ignore(Trigger.Unlock) // Already unlocked, ignore unlock requests .permit(Trigger.Lock, State.Locked); StateMachine sm = new StateMachine<>(State.Locked, config); sm.fire(Trigger.Lock); // Ignored, no exception System.out.println(sm.getState()); // Output: Locked sm.fire(Trigger.Unlock); System.out.println(sm.getState()); // Output: Unlocked ``` ### Response #### Success Response (200) N/A (This is a configuration method, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Add stateless4j Maven Dependency Source: https://github.com/stateless4j/stateless4j/blob/master/README.md Include this dependency in your Maven project to use the stateless4j library. ```xml com.github.stateless4j stateless4j 2.6.0 ``` -------------------------------- ### Execute Action Without State Change with permitInternal Source: https://context7.com/stateless4j/stateless4j/llms.txt Use `permitInternal` to execute an action without changing the state or triggering entry/exit actions. This is useful for handling events that require processing but do not result in a state transition. ```java StateMachineConfig config = new StateMachineConfig<>(); int clickCount = 0; config.configure(State.Idle) .onEntry(() -> System.out.println("Entry action")) .onExit(() -> System.out.println("Exit action")) // Internal transition: action runs, but no entry/exit actions .permitInternal(Trigger.Click, () -> { clickCount++; System.out.println("Click handled, count: " + clickCount); }) .permit(Trigger.Submit, State.Processing); StateMachine sm = new StateMachine<>(State.Idle, config); sm.fire(Trigger.Click); // Output: Click handled, count: 1 sm.fire(Trigger.Click); // Output: Click handled, count: 2 // Note: No "Entry action" or "Exit action" printed - state doesn't change System.out.println(sm.getState()); // Output: Idle ``` -------------------------------- ### StateConfiguration.permitIfElseIgnore() Source: https://context7.com/stateless4j/stateless4j/llms.txt Defines a transition that occurs if a guard condition is met. If the condition is false, the trigger is silently ignored without throwing an exception. ```APIDOC ## StateConfiguration.permitIfElseIgnore() ### Description Accept a trigger and transition if guard is true, otherwise silently ignore (no exception thrown). ### Method `permitIfElseIgnore(Trigger trigger, State destination, Guard guard)` ### Endpoint N/A (This is a configuration method within the StateMachineConfig) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java StateMachineConfig config = new StateMachineConfig<>(); boolean canProceed = false; config.configure(State.Waiting) // If canProceed is false, trigger is ignored silently .permitIfElseIgnore(Trigger.Go, State.Running, () -> canProceed) .permit(Trigger.Cancel, State.Cancelled); ``` ### Response N/A (Configuration method, does not return a response) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### onUnhandledTrigger() - Custom Unhandled Trigger Handling Source: https://context7.com/stateless4j/stateless4j/llms.txt Allows overriding the default exception behavior when an unhandled trigger is fired, providing a custom handler for such events. ```APIDOC ## onUnhandledTrigger() ### Description Override default exception behavior when an unhandled trigger is fired. By default, an IllegalStateException is thrown. ### Method `onUnhandledTrigger` ### Endpoint `StateMachine.onUnhandledTrigger(BiFunction handler)` or `StateMachine.onUnhandledTrigger((state, trigger, args) -> {})` ### Parameters - **handler** (BiFunction or TriFunction) - A function to handle unhandled triggers. It can accept state and trigger, or state, trigger, and arguments. ### Request Example ```java // Custom handler instead of exception sm.onUnhandledTrigger((state, trigger) -> { System.out.println("Warning: Trigger " + trigger + " not valid in state " + state); }); sm.fire(Trigger.Y); // Output: Warning: Trigger Y not valid in state A // Handler with access to trigger parameters sm.onUnhandledTrigger((state, trigger, args) -> { System.out.println("Unhandled: " + trigger + " with params: " + Arrays.toString(args)); }); ``` ### Response N/A (This is a configuration method) ``` -------------------------------- ### Handle Unhandled Triggers in Java Source: https://context7.com/stateless4j/stateless4j/llms.txt Override the default IllegalStateException for unhandled triggers by providing a custom handler. This allows for custom logging or alternative behavior. ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.A).permit(Trigger.X, State.B); StateMachine sm = new StateMachine<>(State.A, config); // Custom handler instead of exception sm.onUnhandledTrigger((state, trigger) -> { System.out.println("Warning: Trigger " + trigger + " not valid in state " + state); }); sm.fire(Trigger.Y); // Output: Warning: Trigger Y not valid in state A // No exception thrown, state unchanged System.out.println(sm.getState()); // Output: A // Handler with access to trigger parameters sm.onUnhandledTrigger((state, trigger, args) -> { System.out.println("Unhandled: " + trigger + " with params: " + Arrays.toString(args)); }); ``` -------------------------------- ### Ignore Triggers in Specific States with ignore Source: https://context7.com/stateless4j/stateless4j/llms.txt Use `ignore` to prevent exceptions when a trigger is fired in a state where it is not defined. This is useful for handling redundant events, such as trying to lock an already locked state. ```java StateMachineConfig config = new StateMachineConfig<>(); config.configure(State.Locked) .ignore(Trigger.Lock) // Already locked, ignore lock requests .permit(Trigger.Unlock, State.Unlocked); config.configure(State.Unlocked) .ignore(Trigger.Unlock) // Already unlocked, ignore unlock requests .permit(Trigger.Lock, State.Locked); StateMachine sm = new StateMachine<>(State.Locked, config); sm.fire(Trigger.Lock); // Ignored, no exception System.out.println(sm.getState()); // Output: Locked sm.fire(Trigger.Unlock); System.out.println(sm.getState()); // Output: Unlocked ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.