org.springframework.statemachine.StateMachine Java Examples

The following examples show how to use org.springframework.statemachine.StateMachine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StateMachineBuilderIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenUseStateMachineBuilder_thenBuildSuccessAndMachineWorks() throws Exception {
    StateMachineBuilder.Builder<String, String> builder = StateMachineBuilder.builder();
    builder.configureStates().withStates()
            .initial("SI")
            .state("S1")
            .end("SF");

    builder.configureTransitions()
            .withExternal()
            .source("SI").target("S1").event("E1")
            .and().withExternal()
            .source("S1").target("SF").event("E2");

    StateMachine machine = builder.build();

    machine.start();

    machine.sendEvent("E1");
    assertEquals("S1", machine.getState().getId());

    machine.sendEvent("E2");
    assertEquals("SF", machine.getState().getId());
}
 
Example #2
Source File: MachineFactory.java    From agile-service-old with Apache License 2.0 6 votes vote down vote up
/**
 * 开始实例
 *
 * @param serviceCode
 * @param stateMachineId
 * @return
 */
public ExecuteResult startInstance(Long organizationId, String serviceCode, Long stateMachineId, InputDTO inputDTO) {
    StateMachine<String, String> instance = buildInstance(organizationId, serviceCode, stateMachineId);
    //存入instanceId,以便执行guard和action
    instance.getExtendedState().getVariables().put(INPUT_DTO, inputDTO);
    //执行初始转换
    Long initTransformId = transformService.getInitTransform(organizationId, stateMachineId).getId();
    instance.sendEvent(initTransformId.toString());

    //缓存实例
    instanceCache.putInstance(serviceCode, stateMachineId, inputDTO.getInstanceId(), instance);
    Object obj = instance.getExtendedState().getVariables().get(EXECUTE_RESULT);
    ExecuteResult executeResult = new ExecuteResult();
    if (obj != null) {
        executeResult = (ExecuteResult) obj;
    } else {
        executeResult.setSuccess(false);
        executeResult.setErrorMessage("触发事件失败");
    }
    return executeResult;
}
 
Example #3
Source File: TaskLauncherStateMachineTests.java    From spring-cloud-deployer-yarn with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitial() throws Exception {
	context.register(Config.class);
	context.refresh();

	TestYarnCloudAppService yarnCloudAppService = new TestYarnCloudAppService();
	TaskExecutor taskExecutor = context.getBean(TaskExecutor.class);
	TaskLauncherStateMachine ycasm = new TaskLauncherStateMachine(yarnCloudAppService, taskExecutor, context, context);
	ycasm.setAutoStart(false);
	StateMachine<String, String> stateMachine = ycasm.buildStateMachine();

	StateMachineTestPlan<String, String> plan =
			StateMachineTestPlanBuilder.<String, String>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates(TaskLauncherStateMachine.STATE_READY)
					.and()
				.build();
	plan.test();
}
 
Example #4
Source File: StateMachinePersistConfigurationTests.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSkipFunction() {
	SkipUnwantedVariablesFunction f = new SkipUnwantedVariablesFunction();

	DefaultExtendedState extendedState = new DefaultExtendedState();
	extendedState.getVariables().put(SkipperVariables.SOURCE_RELEASE, new Object());
	extendedState.getVariables().put(SkipperVariables.TARGET_RELEASE, new Object());
	extendedState.getVariables().put(SkipperVariables.RELEASE, new Object());
	extendedState.getVariables().put(SkipperVariables.RELEASE_ANALYSIS_REPORT, new Object());
	extendedState.getVariables().put(SkipperVariables.ERROR, new Object());
	extendedState.getVariables().put(SkipperVariables.UPGRADE_CUTOFF_TIME, new Object());
	extendedState.getVariables().put(SkipperVariables.UPGRADE_STATUS, new Object());

	StateMachine<SkipperStates, SkipperEvents> stateMachine = Mockito.mock(StateMachine.class);
	Mockito.when(stateMachine.getExtendedState()).thenReturn(extendedState);

	// test that others gets filtered out
	Map<Object, Object> map = f.apply(stateMachine);
	assertThat(map).isNotNull();
	assertThat(map).containsOnlyKeys(SkipperVariables.UPGRADE_CUTOFF_TIME, SkipperVariables.UPGRADE_STATUS);
}
 
Example #5
Source File: AppDeployerStateMachineTests.java    From spring-cloud-deployer-yarn with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitial() throws Exception {
	context.register(Config.class);
	context.refresh();

	TestYarnCloudAppService yarnCloudAppService = new TestYarnCloudAppService();
	TaskExecutor taskExecutor = context.getBean(TaskExecutor.class);
	AppDeployerStateMachine ycasm = new AppDeployerStateMachine(yarnCloudAppService, taskExecutor, context, context);
	ycasm.setAutoStart(false);
	StateMachine<String, String> stateMachine = ycasm.buildStateMachine();

	StateMachineTestPlan<String, String> plan =
			StateMachineTestPlanBuilder.<String, String>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates("READY")
					.and()
				.build();
	plan.test();
}
 
Example #6
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestoreFromInstallUsingInstallProperties() throws Exception {
	Mockito.when(releaseService.install(any(), any(InstallProperties.class))).thenReturn(new Release());

	DefaultExtendedState extendedState = new DefaultExtendedState();
	extendedState.getVariables().put(SkipperEventHeaders.INSTALL_PROPERTIES, new InstallProperties());

	StateMachineContext<SkipperStates, SkipperEvents> stateMachineContext = new DefaultStateMachineContext<>(
			SkipperStates.INSTALL, SkipperEvents.INSTALL, null, extendedState);
	Mockito.when(stateMachineRuntimePersister.read(any())).thenReturn(stateMachineContext);

	StateMachineService<SkipperStates, SkipperEvents> stateMachineService = context.getBean(StateMachineService.class);
	StateMachine<SkipperStates, SkipperEvents> stateMachine = stateMachineService
			.acquireStateMachine("testRestoreFromInstallUsingInstallProperties", false);

	StateMachineTestPlan<SkipperStates, SkipperEvents> plan =
			StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStates(SkipperStates.INITIAL)
					.expectStateChanged(2)
					.and()
				.build();
	plan.test();

	Mockito.verify(upgradeCancelAction, never()).execute(any());
	Mockito.verify(errorAction, never()).execute(any());
}
 
Example #7
Source File: MachineFactory.java    From agile-service-old with Apache License 2.0 5 votes vote down vote up
private StateMachine<String, String> buildInstance(Long organizationId, String serviceCode, Long stateMachineId) {
    StateMachineBuilder.Builder<String, String> builder = instanceCache.getBuilder(stateMachineId);
    if (builder == null) {
        builder = getBuilder(organizationId, serviceCode, stateMachineId);
        logger.info("build StateMachineBuilder successful,stateMachineId:{}", stateMachineId);
        instanceCache.putBuilder(stateMachineId, builder);
    }
    StateMachine<String, String> smInstance = builder.build();
    smInstance.start();
    return smInstance;
}
 
Example #8
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleUpgradeShouldNotError() throws Exception {
	Manifest manifest = new Manifest();
	Release release = new Release();
	release.setManifest(manifest);
	Mockito.when(releaseReportService.createReport(any(), any(), any(boolean.class))).thenReturn(new ReleaseAnalysisReport(
			new ArrayList<>(), new ReleaseDifference(), release, release));
	Mockito.when(upgradeStrategy.checkStatus(any()))
			.thenReturn(true);
	Mockito.when(upgradeStrategyFactory.getUpgradeStrategy(any())).thenReturn(upgradeStrategy);

	UpgradeRequest upgradeRequest = new UpgradeRequest();

	Message<SkipperEvents> message1 = MessageBuilder
			.withPayload(SkipperEvents.UPGRADE)
			.setHeader(SkipperEventHeaders.UPGRADE_REQUEST, upgradeRequest)
			.build();

	StateMachineFactory<SkipperStates, SkipperEvents> factory = context.getBean(StateMachineFactory.class);
	StateMachine<SkipperStates, SkipperEvents> stateMachine = factory.getStateMachine("testSimpleUpgradeShouldNotError");

	StateMachineTestPlan<SkipperStates, SkipperEvents> plan =
			StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates(SkipperStates.INITIAL)
					.and()
				.step()
					.sendEvent(message1)
					.expectStates(SkipperStates.INITIAL)
					.expectStateChanged(9)
					.and()
				.build();
	plan.test();
	Mockito.verify(upgradeCancelAction, never()).execute(any());
	Mockito.verify(errorAction, never()).execute(any());
}
 
Example #9
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteSucceed() throws Exception {
	Mockito.when(releaseService.delete(any(String.class), any(boolean.class))).thenReturn(new Release());
	DeleteProperties deleteProperties = new DeleteProperties();
	Message<SkipperEvents> message1 = MessageBuilder
			.withPayload(SkipperEvents.DELETE)
			.setHeader(SkipperEventHeaders.RELEASE_NAME, "testDeleteSucceed")
			.setHeader(SkipperEventHeaders.RELEASE_DELETE_PROPERTIES, deleteProperties)
			.build();

	StateMachineFactory<SkipperStates, SkipperEvents> factory = context.getBean(StateMachineFactory.class);
	StateMachine<SkipperStates, SkipperEvents> stateMachine = factory.getStateMachine("testDeleteSucceed");

	StateMachineTestPlan<SkipperStates, SkipperEvents> plan =
			StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates(SkipperStates.INITIAL)
					.and()
				.step()
					.sendEvent(message1)
					.expectStates(SkipperStates.INITIAL)
					.expectStateChanged(3)
					.expectStateEntered(SkipperStates.DELETE,
							SkipperStates.DELETE_DELETE,
							SkipperStates.INITIAL)
					.and()
				.build();
	plan.test();

	Mockito.verify(errorAction, never()).execute(any());
}
 
Example #10
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testScaleSucceed() throws Exception {
	Mockito.when(releaseService.scale(any(String.class), any(ScaleRequest.class))).thenReturn(new Release());
	ScaleRequest scaleRequest = new ScaleRequest();
	Message<SkipperEvents> message1 = MessageBuilder
			.withPayload(SkipperEvents.SCALE)
			.setHeader(SkipperEventHeaders.RELEASE_NAME, "testScaleSucceed")
			.setHeader(SkipperEventHeaders.SCALE_REQUEST, scaleRequest)
			.build();

	StateMachineFactory<SkipperStates, SkipperEvents> factory = context.getBean(StateMachineFactory.class);
	StateMachine<SkipperStates, SkipperEvents> stateMachine = factory.getStateMachine("testScaleSucceed");

	StateMachineTestPlan<SkipperStates, SkipperEvents> plan =
			StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates(SkipperStates.INITIAL)
					.and()
				.step()
					.sendEvent(message1)
					.expectStates(SkipperStates.INITIAL)
					.expectStateChanged(3)
					.expectStateEntered(SkipperStates.SCALE,
							SkipperStates.SCALE_SCALE,
							SkipperStates.INITIAL)
					.and()
				.build();
	plan.test();

	Mockito.verify(errorAction, never()).execute(any());
}
 
Example #11
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestoreFromDeleteUsingDeleteProperties() throws Exception {
	Mockito.when(releaseService.delete(nullable(String.class), any(boolean.class))).thenReturn(new Release());
	DeleteProperties deleteProperties = new DeleteProperties();

	DefaultExtendedState extendedState = new DefaultExtendedState();
	extendedState.getVariables().put(SkipperEventHeaders.RELEASE_DELETE_PROPERTIES, deleteProperties);

	StateMachineContext<SkipperStates, SkipperEvents> stateMachineContext = new DefaultStateMachineContext<>(
			SkipperStates.DELETE, SkipperEvents.DELETE, null, extendedState);
	Mockito.when(stateMachineRuntimePersister.read(any())).thenReturn(stateMachineContext);

	StateMachineService<SkipperStates, SkipperEvents> stateMachineService = context.getBean(StateMachineService.class);
	StateMachine<SkipperStates, SkipperEvents> stateMachine = stateMachineService
			.acquireStateMachine("testRestoreFromDeleteUsingDeleteProperties", false);

	StateMachineTestPlan<SkipperStates, SkipperEvents> plan =
			StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStates(SkipperStates.INITIAL)
					.expectStateChanged(2)
					.and()
				.build();
	plan.test();

	Mockito.verify(upgradeCancelAction, never()).execute(any());
	Mockito.verify(errorAction, never()).execute(any());
}
 
Example #12
Source File: StatemachineService.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public void execute(Integer businessId, TurnstileEvents event, Map<String, Object> context) {
    // 利用随记ID创建状态机,创建时没有与具体定义状态机绑定
    StateMachine<TurnstileStates, TurnstileEvents> stateMachine = stateMachineFactory.getStateMachine(UUID.randomUUID());
    stateMachine.start();
    try {
        // 在BizStateMachinePersist的restore过程中,绑定turnstileStateMachine状态机相关事件监听
        stateMachinePersist.restore(stateMachine, businessId);
        // 本处写法较为繁琐,实际为注入Map<String, Object> context内容到message中
        MessageBuilder<TurnstileEvents> messageBuilder = MessageBuilder
                .withPayload(event)
                .setHeader("BusinessId", businessId);
        if (context != null) {
            context.entrySet().forEach(p -> messageBuilder.setHeader(p.getKey(), p.getValue()));
        }
        Message<TurnstileEvents> message = messageBuilder.build();

        // 发送事件,返回是否执行成功
        boolean success = stateMachine.sendEvent(message);
        if (success) {
            stateMachinePersist.persist(stateMachine, businessId);
        } else {
            System.out.println("状态机处理未执行成功,请处理,ID:" + businessId + ",当前context:" + context);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        stateMachine.stop();
    }
}
 
Example #13
Source File: AppDeployerStateMachineTests.java    From spring-cloud-deployer-yarn with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeployShouldPushAndStart() throws Exception {
	context.register(Config.class);
	context.refresh();

	TestYarnCloudAppService yarnCloudAppService = new TestYarnCloudAppService();
	TaskExecutor taskExecutor = context.getBean(TaskExecutor.class);
	AppDeployerStateMachine ycasm = new AppDeployerStateMachine(yarnCloudAppService, taskExecutor, context, context);
	ycasm.setAutoStart(false);
	StateMachine<String, String> stateMachine = ycasm.buildStateMachine();

	Message<String> message = MessageBuilder.withPayload(AppDeployerStateMachine.EVENT_DEPLOY)
			.setHeader(AppDeployerStateMachine.HEADER_APP_VERSION, "app")
			.setHeader(AppDeployerStateMachine.HEADER_CLUSTER_ID, "fakeClusterId")
			.setHeader(AppDeployerStateMachine.HEADER_GROUP_ID, "fakeGroup")
			.setHeader(AppDeployerStateMachine.HEADER_COUNT, 1)
			.setHeader(AppDeployerStateMachine.HEADER_DEFINITION_PARAMETERS, new HashMap<Object, Object>())
			.build();

	StateMachineTestPlan<String, String> plan =
			StateMachineTestPlanBuilder.<String, String>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates(AppDeployerStateMachine.STATE_READY)
					.and()
				.step()
					.sendEvent(message)
					.expectStateChanged(12)
					.expectStates(AppDeployerStateMachine.STATE_READY)
					.and()
				.build();
	plan.test();
}
 
Example #14
Source File: AppDeployerStateMachineTests.java    From spring-cloud-deployer-yarn with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeployShouldPushAndStartLoopWaitInstance() throws Exception {
	context.register(Config.class);
	context.refresh();

	TestYarnCloudAppService yarnCloudAppService = new TestYarnCloudAppService();
	yarnCloudAppService.getInstancesCountBeforeReturn = 2;
	TaskExecutor taskExecutor = context.getBean(TaskExecutor.class);
	AppDeployerStateMachine ycasm = new AppDeployerStateMachine(yarnCloudAppService, taskExecutor, context, context);
	ycasm.setAutoStart(false);
	StateMachine<String, String> stateMachine = ycasm.buildStateMachine();

	Message<String> message = MessageBuilder.withPayload(AppDeployerStateMachine.EVENT_DEPLOY)
			.setHeader(AppDeployerStateMachine.HEADER_APP_VERSION, "app")
			.setHeader(AppDeployerStateMachine.HEADER_CLUSTER_ID, "fakeClusterId")
			.setHeader(AppDeployerStateMachine.HEADER_GROUP_ID, "fakeGroup")
			.setHeader(AppDeployerStateMachine.HEADER_COUNT, 1)
			.setHeader(AppDeployerStateMachine.HEADER_DEFINITION_PARAMETERS, new HashMap<Object, Object>())
			.build();

	StateMachineTestPlan<String, String> plan =
			StateMachineTestPlanBuilder.<String, String>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates(AppDeployerStateMachine.STATE_READY)
					.and()
				.step()
					.sendEvent(message)
					.expectStateChanged(14)
					.expectStates(AppDeployerStateMachine.STATE_READY)
					.and()
				.build();
	plan.test();
}
 
Example #15
Source File: TaskLauncherStateMachineTests.java    From spring-cloud-deployer-yarn with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchShouldPushAndStart() throws Exception {
	context.register(Config.class);
	context.refresh();

	TestYarnCloudAppService yarnCloudAppService = new TestYarnCloudAppService();
	TaskExecutor taskExecutor = context.getBean(TaskExecutor.class);
	TaskLauncherStateMachine ycasm = new TaskLauncherStateMachine(yarnCloudAppService, taskExecutor, context, context);
	ycasm.setAutoStart(false);
	StateMachine<String, String> stateMachine = ycasm.buildStateMachine();

	ArrayList<String> contextRunArgs = new ArrayList<String>();
	Message<String> launchMessage = MessageBuilder.withPayload(TaskLauncherStateMachine.EVENT_LAUNCH)
			.setHeader(TaskLauncherStateMachine.HEADER_APP_VERSION, "fakeApp")
			.setHeader(TaskLauncherStateMachine.HEADER_DEFINITION_PARAMETERS, new HashMap<Object, Object>())
			.setHeader(TaskLauncherStateMachine.HEADER_CONTEXT_RUN_ARGS, contextRunArgs)
			.build();

	StateMachineTestPlan<String, String> plan =
			StateMachineTestPlanBuilder.<String, String>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates(TaskLauncherStateMachine.STATE_READY)
					.and()
				.step()
					.sendEvent(launchMessage)
					.expectStateChanged(6)
					.expectStates(TaskLauncherStateMachine.STATE_READY)
					.and()
				.build();
	plan.test();
}
 
Example #16
Source File: FlowAdapter.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public FlowAdapter(String flowId, StateMachine<S, E> flowMachine, MessageFactory<E> messageFactory, StateConverter<S> stateConverter,
        EventConverter<E> eventConverter, Class<? extends FlowConfiguration<E>> flowConfigClass, FlowEventListener<S, E> flowEventListener) {
    this.flowId = flowId;
    this.flowMachine = flowMachine;
    this.messageFactory = messageFactory;
    this.stateConverter = stateConverter;
    this.eventConverter = eventConverter;
    this.flowConfigClass = flowConfigClass;
    this.flowEventListener = flowEventListener;
}
 
Example #17
Source File: AbstractFlowConfiguration.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public Flow createFlow(String flowId, Long stackId) {
    StateMachine<S, E> sm = stateMachineFactory.getStateMachine();
    FlowEventListener<S, E> fl = (FlowEventListener<S, E>) applicationContext.getBean(FlowEventListener.class, getEdgeConfig().initState,
            getEdgeConfig().finalState, getClass().getSimpleName(), flowId, stackId);
    Flow flow = new FlowAdapter<>(flowId, sm, new MessageFactory<>(), new StateConverterAdapter<>(stateType),
            new EventConverterAdapter<>(eventType), (Class<? extends FlowConfiguration<E>>) getClass(), fl);
    sm.addStateListener(fl);
    return flow;
}
 
Example #18
Source File: FlowStructuredEventHandler.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void stateMachineStopped(StateMachine<S, E> stateMachine) {
    if (!stateMachine.isComplete()) {
        State<S, E> currentState = stateMachine.getState();
        Long currentTime = System.currentTimeMillis();
        String fromId = currentState != null ? currentState.getId().toString() : "unknown";
        FlowDetails flowDetails = new FlowDetails("", flowType, "", flowId, fromId, "unknown", "FLOW_CANCEL",
                lastStateChange == null ? 0L : currentTime - lastStateChange);
        StructuredEvent structuredEvent = structuredFlowEventFactory.createStucturedFlowEvent(stackId, flowDetails, true);
        structuredEventClient.sendStructuredEvent(structuredEvent);
        lastStateChange = currentTime;
    }
}
 
Example #19
Source File: OfflineStateGenerator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void generate() throws Exception {
    StringBuilder builder = new StringBuilder("digraph {\n");
    inject(flowConfiguration, "applicationContext", APP_CONTEXT);
    Flow flow = initializeFlow();
    StateMachine<FlowState, FlowEvent> stateMachine = getStateMachine(flow);
    FlowState init = stateMachine.getInitialState().getId();
    builder.append(generateStartPoint(init, flowConfiguration.getClass().getSimpleName())).append('\n');
    List<Transition<FlowState, FlowEvent>> transitions = (List<Transition<FlowState, FlowEvent>>) stateMachine.getTransitions();
    Map<String, FlowState> transitionsAlreadyDefined = new HashMap<>();
    transitionsAlreadyDefined.put(init.toString(), init);
    while (!transitions.isEmpty()) {
        for (Transition<FlowState, FlowEvent> transition : new ArrayList<>(transitions)) {
            FlowState source = transition.getSource().getId();
            FlowState target = transition.getTarget().getId();
            if (transitionsAlreadyDefined.values().contains(source)) {
                String id = generateTransitionId(source, target, transition.getTrigger().getEvent());
                if (!transitionsAlreadyDefined.keySet().contains(id)) {
                    if (target.action() != null && !transitionsAlreadyDefined.values().contains(target)) {
                        builder.append(generateState(target, target.action().getSimpleName())).append('\n');
                    }
                    builder.append(generateTransition(source, target, transition.getTrigger().getEvent())).append('\n');
                    transitionsAlreadyDefined.put(id, target);
                }
                transitions.remove(transition);
            }
        }
    }
    saveToFile(builder.append('}').toString());
}
 
Example #20
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestoreFromInstallUsingInstallRequest() throws Exception {
	Mockito.when(releaseService.install(any(InstallRequest.class))).thenReturn(new Release());

	DefaultExtendedState extendedState = new DefaultExtendedState();
	extendedState.getVariables().put(SkipperEventHeaders.INSTALL_REQUEST, new InstallRequest());

	StateMachineContext<SkipperStates, SkipperEvents> stateMachineContext = new DefaultStateMachineContext<>(
			SkipperStates.INSTALL, SkipperEvents.INSTALL, null, extendedState);
	Mockito.when(stateMachineRuntimePersister.read(any())).thenReturn(stateMachineContext);

	StateMachineService<SkipperStates, SkipperEvents> stateMachineService = context.getBean(StateMachineService.class);
	StateMachine<SkipperStates, SkipperEvents> stateMachine = stateMachineService
			.acquireStateMachine("testRestoreFromInstallUsingInstallRequest", false);

	StateMachineTestPlan<SkipperStates, SkipperEvents> plan =
			StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStates(SkipperStates.INITIAL)
					.expectStateChanged(2)
					.and()
				.build();
	plan.test();

	Mockito.verify(upgradeCancelAction, never()).execute(any());
	Mockito.verify(errorAction, never()).execute(any());
}
 
Example #21
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestoreFromUpgradeUsingUpgradeRequest() throws Exception {
	Manifest manifest = new Manifest();
	Release release = new Release();
	release.setManifest(manifest);
	Mockito.when(releaseReportService.createReport(any(), any(), any(boolean.class))).thenReturn(new ReleaseAnalysisReport(
			new ArrayList<>(), new ReleaseDifference(), release, release));
	Mockito.when(upgradeStrategy.checkStatus(any()))
			.thenReturn(true);
	Mockito.when(upgradeStrategyFactory.getUpgradeStrategy(any())).thenReturn(upgradeStrategy);

	DefaultExtendedState extendedState = new DefaultExtendedState();
	extendedState.getVariables().put(SkipperEventHeaders.UPGRADE_REQUEST, new UpgradeRequest());

	StateMachineContext<SkipperStates, SkipperEvents> stateMachineContext = new DefaultStateMachineContext<>(
			SkipperStates.UPGRADE, SkipperEvents.UPGRADE, null, extendedState);
	Mockito.when(stateMachineRuntimePersister.read(any())).thenReturn(stateMachineContext);

	StateMachineService<SkipperStates, SkipperEvents> stateMachineService = context.getBean(StateMachineService.class);
	StateMachine<SkipperStates, SkipperEvents> stateMachine = stateMachineService
			.acquireStateMachine("testRestoreFromUpgradeUsingUpgradeRequest", false);

	StateMachineTestPlan<SkipperStates, SkipperEvents> plan =
			StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStates(SkipperStates.INITIAL)
					.expectStateChanged(8)
					.and()
				.build();
	plan.test();
	Mockito.verify(upgradeCancelAction, never()).execute(any());
	Mockito.verify(errorAction, never()).execute(any());
}
 
Example #22
Source File: InstanceCache.java    From agile-service-old with Apache License 2.0 5 votes vote down vote up
/**
 * 缓存状态机实例
 */
public void putInstance(String serviceCode, Long stateMachineId, Long instanceId, StateMachine<String, String> stateMachineInstance) {
    String key = serviceCode + ":" + stateMachineId + ":" + instanceId;
    instanceMap.put(key, stateMachineInstance);
    aliveMap.put(key, 2);
    Set<String> instanceKeys = stateMachineMap.get(stateMachineId);
    if (instanceKeys != null) {
        instanceKeys.add(key);
    } else {
        instanceKeys = new HashSet<>();
        instanceKeys.add(key);
        stateMachineMap.put(stateMachineId, instanceKeys);
    }
}
 
Example #23
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleInstallShouldNotError() throws Exception {
	Mockito.when(packageService.downloadPackage(any()))
			.thenReturn(new org.springframework.cloud.skipper.domain.Package());
	Mockito.when(releaseService.install(any(), any())).thenReturn(new Release());

	Message<SkipperEvents> message = MessageBuilder
		.withPayload(SkipperEvents.INSTALL)
		.setHeader(SkipperEventHeaders.PACKAGE_METADATA, new PackageMetadata())
		.setHeader(SkipperEventHeaders.INSTALL_PROPERTIES, new InstallProperties())
		.setHeader(SkipperEventHeaders.VERSION, 1)
		.build();

	StateMachineFactory<SkipperStates, SkipperEvents> factory = context.getBean(StateMachineFactory.class);
	StateMachine<SkipperStates, SkipperEvents> stateMachine = factory.getStateMachine("testInstall");

	StateMachineTestPlan<SkipperStates, SkipperEvents> plan =
			StateMachineTestPlanBuilder.<SkipperStates, SkipperEvents>builder()
				.defaultAwaitTime(10)
				.stateMachine(stateMachine)
				.step()
					.expectStateMachineStarted(1)
					.expectStates(SkipperStates.INITIAL)
					.and()
				.step()
					.sendEvent(message)
					.expectStates(SkipperStates.INITIAL)
					.expectStateChanged(3)
					.expectStateEntered(SkipperStates.INSTALL,
							SkipperStates.INSTALL_INSTALL,
							SkipperStates.INITIAL)
					.and()
				.build();
	plan.test();

	Mockito.verify(errorAction, never()).execute(any());
}
 
Example #24
Source File: StateMachineTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void testFactory() {
	StateMachineFactory<SkipperStates, SkipperEvents> factory = context.getBean(StateMachineFactory.class);
	assertThat(factory).isNotNull();
	StateMachine<SkipperStates, SkipperEvents> stateMachine = factory.getStateMachine("testFactory");
	assertThat(stateMachine).isNotNull();
}
 
Example #25
Source File: InstanceCache.java    From agile-service-old with Apache License 2.0 5 votes vote down vote up
/**
 * 获取单个实例
 */
public StateMachine<String, String> getInstance(String serviceCode, Long stateMachineId, Long instanceId) {
    String key = serviceCode + ":" + stateMachineId + ":" + instanceId;
    Integer aliveCount = aliveMap.get(key);
    if (aliveCount != null && aliveCount != 0) {
        aliveMap.put(key, aliveCount + 1);
    }
    return instanceMap.get(key);
}
 
Example #26
Source File: StateMachinePersistConfiguration.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public Map<Object, Object> apply(StateMachine<SkipperStates, SkipperEvents> stateMachine) {
	return stateMachine.getExtendedState().getVariables().entrySet().stream().filter(e -> {
		return !(ObjectUtils.nullSafeEquals(e.getKey(), SkipperVariables.SOURCE_RELEASE)
				|| ObjectUtils.nullSafeEquals(e.getKey(), SkipperVariables.TARGET_RELEASE)
				|| ObjectUtils.nullSafeEquals(e.getKey(), SkipperVariables.RELEASE)
				|| ObjectUtils.nullSafeEquals(e.getKey(), SkipperVariables.RELEASE_ANALYSIS_REPORT)
				|| ObjectUtils.nullSafeEquals(e.getKey(), SkipperVariables.ERROR));
	}).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
}
 
Example #27
Source File: StateMachineTest.java    From spring-statemachine-learning with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    StateMachine<StateEnum, EventEnum> stateMachine = stateMachineFactory.getStateMachine();
    stateMachine.start();
    Assert.assertEquals(stateMachine.getState().getId(), StateEnum.S1);
    stateMachine.sendEvent(EventEnum.E1);
    Assert.assertEquals(stateMachine.getState().getId(), StateEnum.S1);
    stateMachine.sendEvent(EventEnum.E2);
    Assert.assertEquals(stateMachine.getState().getId(), StateEnum.S1);
}
 
Example #28
Source File: RedisPersistConfigTest.java    From spring-statemachine-learning with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    StateMachine<StateEnum, EventEnum> stateMachine = stateMachineAdapter.create();
    Assert.assertEquals(stateMachine.getState().getId(), StateEnum.S1);
    stateMachine.sendEvent(EventEnum.E1);
    stateMachineAdapter.persist(stateMachine, "1");
    stateMachine = stateMachineAdapter.restore("1");
    Assert.assertEquals(stateMachine.getState().getId(), StateEnum.S2);
    StateMachine<StateEnum, EventEnum> stateMachine2 = stateMachineAdapter.create();
    stateMachineAdapter.persist(stateMachine2, "2");
    stateMachine = stateMachineAdapter.restore("2");
    Assert.assertEquals(stateMachine.getState().getId(), StateEnum.S1);
}
 
Example #29
Source File: StateMachineInEntityPersistTest.java    From spring-statemachine-learning with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    StateMachine<StateEnum, EventEnum> stateMachine = stateMachineAdapter.create();
    Assert.assertEquals(stateMachine.getState().getId(), StateEnum.S1);
    EnityWithSateMachine enityWithSateMachine = new EnityWithSateMachine();
    stateMachine.sendEvent(EventEnum.E1);
    stateMachineAdapter.persist(stateMachine, enityWithSateMachine);
    StateMachine<StateEnum, EventEnum> stateMachine1 = stateMachineAdapter.restore(enityWithSateMachine);
    Assert.assertEquals(stateMachine1.getState().getId(), StateEnum.S2);
}
 
Example #30
Source File: SpringBootStateMachineApplication.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public SpringBootStateMachineApplication(StateMachine<States, Events> stateMachine) {
    this.stateMachine = stateMachine;
}