Remove dependency to Spring Shell

This commit updates the samples to use Java's
standard CLI utilities instead of Spring Shell.

Resolves #1184
This commit is contained in:
Mahmoud Ben Hassine
2025-04-15 14:08:19 +02:00
parent 5170c0e2d2
commit 1a017dced2
71 changed files with 733 additions and 2024 deletions

View File

@@ -8,7 +8,7 @@ dependencies {
management platform(project(":spring-statemachine-platform"))
implementation project(':spring-statemachine-samples-common')
implementation project(':spring-statemachine-core')
implementation 'org.springframework.shell:spring-shell-core'
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation(testFixtures(project(':spring-statemachine-core')))
testImplementation (project(':spring-statemachine-test'))
testImplementation 'org.hamcrest:hamcrest-core'

View File

@@ -22,6 +22,7 @@ import java.lang.annotation.Target;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.support.MessageBuilder;
@@ -39,7 +40,7 @@ import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Mono;
@Configuration
@SpringBootApplication(scanBasePackages = "demo")
public class Application {
@Configuration

View File

@@ -15,24 +15,32 @@
*/
package demo.tasks;
import demo.BasicCommand;
import demo.Command;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.shell.command.annotation.Command;
import org.springframework.shell.command.annotation.Option;
import demo.AbstractStateMachineCommands;
import demo.tasks.Application.Events;
import demo.tasks.Application.States;
import reactor.core.publisher.Mono;
@Command
@Configuration
public class StateMachineCommands extends AbstractStateMachineCommands<States, Events> {
@Command(command = "sm event", description = "Sends an event to a state machine")
public String event(@Option(longNames = { "", "event" }, required = true, description = "The event") final Events event) {
getStateMachine()
.sendEvent(Mono.just(MessageBuilder
.withPayload(event).build()))
.subscribe();
return "Event " + event + " send";
@Bean
public Command event() {
return new BasicCommand("event", "Sends an event to a state machine") {
@Override
public String execute(String[] args) {
Events event = Events.valueOf(args[0]);
getStateMachine()
.sendEvent(Mono.just(MessageBuilder
.withPayload(event).build()))
.subscribe();
return "Event " + event + " sent";
}
};
}
}
}

View File

@@ -15,34 +15,60 @@
*/
package demo.tasks;
import demo.BasicCommand;
import demo.Command;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.command.annotation.Command;
import org.springframework.shell.command.annotation.Option;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Command
@Configuration
public class TasksCommands {
@Autowired
private Tasks tasks;
@Command(command = "tasks run", description = "Run tasks")
public void run() {
tasks.run();
@Bean
public Command run() {
return new BasicCommand("run", "Run tasks") {
@Override
public String execute(String[] args) {
tasks.run();
return "Tasks started";
}
};
}
@Command(command = "tasks list", description = "List tasks")
public String list() {
return tasks.toString();
@Bean
public Command list() {
return new BasicCommand("list", "List tasks") {
@Override
public String execute(String[] args) {
return tasks.toString();
}
};
}
@Command(command = "tasks fix", description = "Fix tasks")
public void fix() {
tasks.fix();
@Bean
public Command fix() {
return new BasicCommand("fix", "Fix tasks") {
@Override
public String execute(String[] args) {
tasks.fix();
return "Tasks fixed";
}
};
}
@Command(command = "tasks fail", description = "Fail task")
public void fail(@Option(longNames = {"", "task"}, description = "Task id") String task) {
tasks.fail(task);
@Bean
public Command fail() {
return new BasicCommand("fail [taskId]", "Fail task with [taskId]") {
@Override
public String execute(String[] args) {
String taskId = args[0];
tasks.fail(taskId);
return "Task " + taskId + " failed";
}
};
}
}

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="demo" />
</beans>

View File

@@ -0,0 +1 @@
spring.main.allow-bean-definition-overriding=true

View File

@@ -1,30 +0,0 @@
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package demo.tasks;
import reactor.blockhound.BlockHound.Builder;
import reactor.blockhound.integration.BlockHoundIntegration;
public class StateMachineBlockHoundIntegration implements BlockHoundIntegration {
@Override
public void applyTo(Builder builder) {
// whitelisting some blocking calls in tests
builder
.allowBlockingCallsInside("demo.tasks.Tasks", "sleep")
.allowBlockingCallsInside("java.util.concurrent.locks.LockSupport", "park");
}
}

View File

@@ -1,243 +0,0 @@
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package demo.tasks;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.statemachine.TestUtils.doStartAndAssert;
import static org.springframework.statemachine.TestUtils.doStopAndAssert;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.statemachine.ObjectStateMachine;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.StateMachineSystemConstants;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.transition.Transition;
import org.springframework.util.StringUtils;
import demo.CommonConfiguration;
import demo.tasks.Application.Events;
import demo.tasks.Application.States;
public class TasksTests {
private final static Log log = LogFactory.getLog(TasksTests.class);
private AnnotationConfigApplicationContext context;
private StateMachine<States,Events> machine;
private Tasks tasks;
private TestListener listener;
@Test
public void testInitialState() throws InterruptedException {
Map<Object, Object> variables = machine.getExtendedState().getVariables();
assertThat(variables).isEmpty();
}
@Test
public void testRunOnce() throws InterruptedException {
listener.reset(8, 8, 0);
tasks.run();
assertThat(listener.stateEnteredLatch.await(8, TimeUnit.SECONDS)).isTrue();
assertThat(machine.getState().getIds()).containsExactly(States.READY);
Map<Object, Object> variables = machine.getExtendedState().getVariables();
assertThat(variables).hasSize(3);
}
@Test
public void testRunTwice() throws InterruptedException {
listener.reset(8, 8, 0);
tasks.run();
assertThat(listener.stateEnteredLatch.await(8, TimeUnit.SECONDS)).isTrue();
assertThat(machine.getState().getIds()).containsExactly(States.READY);
Map<Object, Object> variables = machine.getExtendedState().getVariables();
assertThat(variables).hasSize(3);
listener.reset(8, 8, 0);
tasks.run();
assertThat(listener.stateEnteredLatch.await(8, TimeUnit.SECONDS)).isTrue();
assertThat(machine.getState().getIds()).containsExactly(States.READY);
variables = machine.getExtendedState().getVariables();
assertThat(variables).hasSize(3);
}
@Test
@Tag("smoke")
public void testRunSmoke() throws InterruptedException {
for (int i = 0; i < 20; i++) {
log.info("testRunSmoke SMOKE START " + i);
listener.reset(8, 8, 0);
tasks.run();
boolean await = listener.stateEnteredLatch.await(8, TimeUnit.SECONDS);
String reason = "Machine was " + machine + " " + StringUtils.collectionToCommaDelimitedString(listener.statesEntered);
assertThat(await).isTrue().withFailMessage(reason);
assertThat(machine.getState().getIds()).containsExactly(States.READY);
log.info("testRunSmoke SMOKE STOP " + i);
}
}
@Test
public void testFailAutomaticFix() throws InterruptedException {
listener.reset(10, 0, 0);
tasks.fail("T1");
tasks.run();
assertThat(listener.stateChangedLatch.await(6, TimeUnit.SECONDS)).isTrue();
assertThat(listener.stateChangedCount).isEqualTo(10);
assertThat(machine.getState().getIds()).containsExactly(States.READY);
}
@Test
public void testFailManualFix() throws InterruptedException {
listener.reset(10, 0, 0);
tasks.fail("T2");
tasks.run();
assertThat(listener.stateChangedLatch.await(6, TimeUnit.SECONDS)).isTrue();
Map<Object, Object> variables = machine.getExtendedState().getVariables();
assertThat(variables).hasSize(3);
assertThat(machine.getState().getIds()).containsExactly(States.ERROR, States.MANUAL);
listener.reset(1, 0, 0);
tasks.fix();
assertThat(listener.stateChangedLatch.await(6, TimeUnit.SECONDS)).isTrue();
assertThat(machine.getState().getIds()).containsExactly(States.READY);
}
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() throws Exception {
context = new AnnotationConfigApplicationContext();
context.register(CommonConfiguration.class, Application.class, TestConfig.class);
context.refresh();
machine = context.getBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, ObjectStateMachine.class);
tasks = context.getBean(Tasks.class);
listener = context.getBean(TestListener.class);
doStartAndAssert(machine);
assertThat(listener.stateChangedLatch.await(1, TimeUnit.SECONDS)).isTrue();
assertThat(listener.stateChangedCount).isEqualTo(1);
assertThat(machine.getState().getIds()).containsExactly(States.READY);
}
@AfterEach
public void clean() {
doStopAndAssert(machine);
context.close();
context = null;
machine = null;
tasks = null;
listener = null;
}
static class TestConfig {
@Autowired
private StateMachine<States,Events> machine;
@Bean
public StateMachineListener<States, Events> stateMachineListener() {
TestListener listener = new TestListener();
machine.addStateListener(listener);
return listener;
}
}
static class TestListener extends StateMachineListenerAdapter<States, Events> {
final Object lock = new Object();
volatile CountDownLatch stateChangedLatch = new CountDownLatch(1);
volatile CountDownLatch stateEnteredLatch = new CountDownLatch(2);
volatile CountDownLatch stateExitedLatch = new CountDownLatch(0);
volatile CountDownLatch transitionLatch = new CountDownLatch(0);
volatile int stateChangedCount = 0;
volatile int transitionCount = 0;
List<State<States, Events>> statesEntered = new ArrayList<State<States,Events>>();
List<State<States, Events>> statesExited = new ArrayList<State<States,Events>>();
@Override
public void stateChanged(State<States, Events> from, State<States, Events> to) {
synchronized (lock) {
stateChangedCount++;
stateChangedLatch.countDown();
}
}
@Override
public void stateEntered(State<States, Events> state) {
synchronized (lock) {
statesEntered.add(state);
stateEnteredLatch.countDown();
}
}
@Override
public void stateExited(State<States, Events> state) {
synchronized (lock) {
statesExited.add(state);
stateExitedLatch.countDown();
}
}
@Override
public void transitionEnded(Transition<States, Events> transition) {
synchronized (lock) {
transitionCount++;
transitionLatch.countDown();
}
}
public void reset(int c1, int c2, int c3) {
reset(c1, c2, c3, 0);
}
public void reset(int c1, int c2, int c3, int c4) {
synchronized (lock) {
stateChangedLatch = new CountDownLatch(c1);
stateEnteredLatch = new CountDownLatch(c2);
stateExitedLatch = new CountDownLatch(c3);
transitionLatch = new CountDownLatch(c4);
stateChangedCount = 0;
transitionCount = 0;
statesEntered.clear();
statesExited.clear();
}
}
}
}

View File

@@ -1,13 +0,0 @@
<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d{ABSOLUTE} %5p %t %c{2} [%t] - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.springframework.statemachine" level="debug"/>
<Root level="info">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
</Configuration>

View File

@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %t %m%n</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="CONSOLE" />
</root>
<logger name="org.springframework.statemachine" level="DEBUG"/>
</configuration>