├── .java-version ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── tsm4j ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── tsm4j │ │ │ └── core │ │ │ ├── StateListener.java │ │ │ ├── StateMachineContext.java │ │ │ ├── StateMachine.java │ │ │ ├── ObjectContainer.java │ │ │ ├── DependencyQueue.java │ │ │ ├── StateMachineBuilder.java │ │ │ ├── StateMachineContextImpl.java │ │ │ ├── DependencyMap.java │ │ │ ├── StateMachineBuilderImpl.java │ │ │ └── StateMachineImpl.java │ └── test │ │ └── java │ │ └── com │ │ └── tsm4j │ │ └── core │ │ ├── DependencyMapTest.java │ │ └── StateMachineTest.java └── build.gradle ├── .gitattributes ├── settings.gradle ├── DEVELOPMENT.md ├── README.md ├── gradlew.bat ├── gradlew └── LICENSE /.java-version: -------------------------------------------------------------------------------- 1 | 1.8 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weilueluo/tsm4j/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore Gradle project-specific cache directory 2 | .gradle 3 | 4 | # Ignore Gradle build output directory 5 | build 6 | 7 | .idea -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/StateListener.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | @FunctionalInterface 4 | public interface StateListener> { 5 | 6 | void accept(StateMachineContext context); 7 | } 8 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | # 4 | # Linux start script should use lf 5 | /gradlew text eol=lf 6 | 7 | # These are Windows script files and should use crlf 8 | *.bat text eol=crlf 9 | 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/StateMachineContext.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import java.util.Set; 4 | 5 | public interface StateMachineContext> { 6 | 7 | void queue(S state); 8 | 9 | int getReachedCount(S state); 10 | 11 | boolean reached(S state); 12 | 13 | Set getAllStates(); 14 | 15 | S getLatestState(); 16 | } 17 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * 6 | * Detailed information about configuring a multi-project build in Gradle can be found 7 | * in the user manual at https://docs.gradle.org/7.6/userguide/multi_project_builds.html 8 | */ 9 | 10 | rootProject.name = 'tsm4j' 11 | include('tsm4j') 12 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/StateMachine.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | public interface StateMachine> { 7 | StateMachineContext send(List states); 8 | 9 | StateMachineContext send(S state); 10 | 11 | void queue(List states); 12 | 13 | StateMachineContext process(); 14 | 15 | Set getAllStates(); 16 | 17 | StateMachineBuilder toBuilder(); 18 | 19 | boolean reached(S state); 20 | 21 | int getReachedCount(S state); 22 | } 23 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/ObjectContainer.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import java.util.Objects; 4 | 5 | /* 6 | * This class is to give the wrapped object a unique hashcode 7 | * */ 8 | class ObjectContainer { 9 | 10 | private final T obj; 11 | 12 | ObjectContainer(T obj) { 13 | this.obj = obj; 14 | } 15 | 16 | T get() { 17 | return this.obj; 18 | } 19 | 20 | @Override 21 | public int hashCode() { 22 | return 31 * super.hashCode() + Objects.hashCode(this.obj); 23 | } 24 | 25 | @Override 26 | public boolean equals(Object obj) { 27 | return obj != null && getClass().equals(obj.getClass()) && hashCode() == obj.hashCode(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/DependencyQueue.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | /* 8 | * Wrap DependencyMap, provides an in-memory buffer of the made available keys 9 | * */ 10 | class DependencyQueue { 11 | private final DependencyMap dependencyMap; 12 | private final LinkedList buffer; 13 | 14 | DependencyQueue(Map> dependencies) { 15 | this.dependencyMap = new DependencyMap<>(dependencies); 16 | this.buffer = new LinkedList<>(); 17 | } 18 | 19 | void satisfy(D dep) { 20 | this.buffer.addAll(this.dependencyMap.satisfy(dep)); 21 | } 22 | 23 | boolean isEmpty() { 24 | return this.buffer.isEmpty(); 25 | } 26 | 27 | K pop() { 28 | return this.buffer.pop(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /DEVELOPMENT.md: -------------------------------------------------------------------------------- 1 | # Development 2 | 3 | ## Publish New Version 4 | 5 | 1. Update new version in `tsm4j/build.gradle` and `README.md` 6 | 2. Delete the old `tsm4j/build` directory if any, and create a new version locally 7 | ```bash 8 | rm -r tsm4j/build 9 | ./gradlew publishTsm4jPublicationToMavenRepository 10 | ``` 11 | > :note: If you see 12 | > ``` 13 | > > Cannot perform signing task ':tsm4j:signTsm4jPublication' because it has no configured signatory 14 | > ``` 15 | > This means you do not have the right settings in `~/.gradle/gradle.properties`, i.e. `signing.keyId`, `signing.password`, and `signing.secretKeyRingFile`. 16 | > For me, this probably means I am not running the command in my wsl2 ubuntu. 17 | 3. Zip the release files 18 | ```bash 19 | cd tsm4j/build/repos/releases 20 | zip release.zip ./com/tsm4j/tsm4j/1.1.0/* 21 | cd - 22 | ``` 23 | 4. Open https://central.sonatype.com/publishing 24 | 1. sign in (continue with google) 25 | 2. upload 26 | 3. wait for validation 27 | 4. publish 28 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/StateMachineBuilder.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import java.util.Set; 4 | 5 | public interface StateMachineBuilder> { 6 | 7 | StateMachineBuilder addTransition(S fromState, S toState); 8 | 9 | StateMachineBuilder addTransition(Set requiredStates, S toStates); 10 | 11 | StateMachineBuilder removeTransition(S fromState, S toState); 12 | 13 | StateMachineBuilder removeTransition(Set requiredStates, S toStates); 14 | 15 | StateMachineBuilder addListener(S requiredState, StateListener listener); 16 | 17 | StateMachineBuilder addListener(Set requiredStates, StateListener listener); 18 | 19 | StateMachineBuilder addListener(StateListener listener); 20 | 21 | StateMachineBuilder removeListener(Set requiredStates, StateListener listener); 22 | 23 | StateMachineBuilder removeAllListeners(Set requiredStates); 24 | 25 | StateMachine build(); 26 | 27 | static > StateMachineBuilder from(Class clazz) { 28 | return StateMachineBuilderImpl.statesFrom(clazz); 29 | } 30 | 31 | static > StateMachineBuilder from(StateMachine stateMachine) { 32 | return StateMachineBuilderImpl.from(stateMachine); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/StateMachineContextImpl.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import java.util.HashMap; 4 | import java.util.LinkedList; 5 | import java.util.Map; 6 | import java.util.Set; 7 | import java.util.function.Consumer; 8 | 9 | public class StateMachineContextImpl> implements StateMachineContext { 10 | 11 | private final Map stateCountMap; 12 | 13 | private final Set allStates; 14 | 15 | private final LinkedList queuedStates; 16 | 17 | private S lastState; 18 | 19 | StateMachineContextImpl(Set allStates) { 20 | this.stateCountMap = new HashMap<>(); 21 | this.allStates = allStates; 22 | this.queuedStates= new LinkedList<>(); 23 | } 24 | 25 | @Override 26 | public void queue(S state) { 27 | this.queuedStates.add(state); 28 | } 29 | 30 | void consumeQueuedStates(Consumer stateConsumer) { 31 | while (!this.queuedStates.isEmpty()) { 32 | stateConsumer.accept(this.queuedStates.pop()); 33 | } 34 | } 35 | 36 | @Override 37 | public int getReachedCount(S state) { 38 | return this.stateCountMap.getOrDefault(state, 0); 39 | } 40 | 41 | @Override 42 | public boolean reached(S state) { 43 | return getReachedCount(state) != 0; 44 | } 45 | 46 | @Override 47 | public Set getAllStates() { 48 | return this.allStates; 49 | } 50 | 51 | @Override 52 | public S getLatestState() { 53 | return this.lastState; 54 | } 55 | 56 | 57 | void onStateReached(S state) { 58 | this.stateCountMap.compute(state, (s, count) -> count == null ? 1 : count + 1); 59 | this.lastState = state; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tsm4j 2 | 3 | A tiny, in-memory, zero dependency state machine library 4 | 5 | ## Install 6 | 7 | ### Gradle 8 | ``` 9 | implementation 'com.tsm4j:tsm4j:1.1.0' 10 | ``` 11 | 12 | ### Maven 13 | ```xml 14 | 15 | com.tsm4j 16 | tsm4j 17 | 1.1.0 18 | 19 | ``` 20 | 21 | ## Usage 22 | 23 | ### Example 24 | An example of defining and running a state machine: 25 | 26 | ```java 27 | StateMachine stateMachine = StateMachineBuilder.from(TestState.class) 28 | .addTransition(TestState.HUNGRY, TestState.MAKE_FOOD) 29 | .addTransition(TestState.MAKE_FOOD, TestState.FOOD_IS_READY) 30 | .addTransition(TestState.FOOD_IS_READY, TestState.EAT_FOOD) 31 | .addTransition(TestState.EAT_FOOD, TestState.FULL) 32 | .build(); 33 | 34 | assertThat(stateMachine.send(TestState.HUNGRY).reached(TestState.FULL)).isTrue(); 35 | ``` 36 | 37 | You can bind a listener which is called whenever some state(s) is reached 38 | ```java 39 | StateMachine stateMachine = StateMachineBuilder.from(TestState.class) 40 | .addTransition(TestState.NO_FOOD, TestState.MAKE_FOOD) 41 | .addListener(TestState.MAKE_FOOD, context -> { 42 | System.out.println("making food..."); 43 | context.queue(TestState.FOOD_IS_READY); 44 | }) 45 | .addListener(debugLoggingListener()) 46 | .build(); 47 | 48 | assertThat(stateMachine.send(TestState.NO_FOOD).reached(TestState.FOOD_IS_READY)).isTrue(); 49 | ``` 50 | 51 | ### More Examples 52 | see tsm4j/test. 53 | 54 | ## About the older version 55 | In short, it was going in the wrong direction, we should separate state machine from action. 56 | 57 | ## Contributing 58 | Feel free to open up an issue for a feature request, bug report, or pull request. 59 | -------------------------------------------------------------------------------- /tsm4j/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | * 4 | * This generated file contains a sample Java library project to get you started. 5 | * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle 6 | * User Manual available at https://docs.gradle.org/7.6/userguide/building_java_projects.html 7 | */ 8 | 9 | plugins { 10 | // Apply the java-library plugin for API and implementation separation. 11 | id 'java-library' 12 | id 'maven-publish' 13 | id 'signing' 14 | } 15 | 16 | repositories { 17 | // Use Maven Central for resolving dependencies. 18 | mavenCentral() 19 | } 20 | 21 | java { 22 | toolchain { 23 | languageVersion = JavaLanguageVersion.of(8) 24 | } 25 | withSourcesJar() 26 | withJavadocJar() 27 | } 28 | 29 | group = 'com.tsm4j' 30 | archivesBaseName = 'tsm4j' 31 | version = '1.1.0' 32 | 33 | 34 | publishing { 35 | publications { 36 | tsm4j(MavenPublication) { 37 | from components.java 38 | pom { 39 | name = 'tsm4j' 40 | description = 'Typed State Machine for Java' 41 | url = 'https://github.com/weilueluo/tsm4j' 42 | licenses { 43 | license { 44 | name = 'The Apache License, Version 2.0' 45 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 46 | } 47 | } 48 | developers { 49 | developer { 50 | id = 'weilueluo' 51 | name = 'Weilue Luo' 52 | email = 'luoweilue@gmail.com' 53 | } 54 | } 55 | scm { 56 | connection = 'scm:git:git://github.com/weilueluo/tsm4j.git' 57 | developerConnection = 'scm:git:ssh://github.com/weilueluo/tsm4j.git' 58 | url = 'https://github.com/weilueluo/tsm4j' 59 | } 60 | } 61 | } 62 | } 63 | repositories { 64 | maven { 65 | def releasesRepoUrl = layout.buildDirectory.dir('repos/releases') 66 | def snapshotsRepoUrl = layout.buildDirectory.dir('repos/snapshots') 67 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl 68 | } 69 | } 70 | } 71 | 72 | signing { 73 | sign publishing.publications.tsm4j 74 | } 75 | 76 | dependencies { 77 | testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1' 78 | testImplementation 'org.assertj:assertj-core:3.25.1' 79 | } 80 | 81 | publishTsm4jPublicationToMavenRepository { 82 | dependsOn test 83 | } 84 | 85 | tasks.named('test') { 86 | useJUnitPlatform() 87 | } 88 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/DependencyMap.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.HashSet; 6 | import java.util.LinkedList; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | /* 11 | * Manage dependency of type K and its set of dependencies of type D 12 | * */ 13 | class DependencyMap { 14 | private final Map> k2d; 15 | private final Map> d2k; 16 | private final Map>> k2ds; 17 | 18 | DependencyMap(Map> dependencies) { 19 | this.k2d = new HashMap<>(dependencies); 20 | this.d2k = initReverseMap(dependencies); 21 | this.k2ds = initDependenciesMap(dependencies); 22 | } 23 | 24 | public static Builder builder() { 25 | return new Builder<>(); 26 | } 27 | 28 | private static Map> initReverseMap(Map> k2d) { 29 | Map> revMap = new HashMap<>(); 30 | k2d.forEach((key, value) -> value.forEach(dep -> revMap.computeIfAbsent(dep, k -> new HashSet<>()).add(key))); 31 | return Collections.unmodifiableMap(revMap); 32 | } 33 | 34 | private static Map>> initDependenciesMap(Map> k2d) { 35 | Map>> depMap = new HashMap<>(); 36 | k2d.forEach((key, value) -> depMap.put(key, new LinkedList<>())); 37 | return Collections.unmodifiableMap(depMap); 38 | } 39 | 40 | public Set satisfy(D dep) { 41 | Set freed = new HashSet<>(); // the set of freed keys after removing this dependency 42 | 43 | // we loop through the keys that depends on this dependency 44 | Set affectedKeys = this.d2k.get(dep); 45 | if (affectedKeys != null) { 46 | affectedKeys.forEach(affectedKey -> { 47 | // here loop through each dependency, and see if we can release the key 48 | // if no existing dependency set for the key contains dependency, we will create a new set of dependency for it to remove 49 | boolean notRemoved = true; 50 | 51 | LinkedList> depsList = this.k2ds.get(affectedKey); 52 | 53 | for (Set deps : depsList) { 54 | if (deps.remove(dep)) { 55 | notRemoved = false; 56 | if (deps.isEmpty()) { 57 | freed.add(affectedKey); 58 | // if its empty, it has to be the first one, so we remove it 59 | depsList.removeFirst(); 60 | } 61 | break; 62 | } 63 | } 64 | 65 | if (notRemoved) { 66 | // the dependency is referring a fresh set of dependencies 67 | Set newDeps = new HashSet<>(this.k2d.get(affectedKey)); 68 | newDeps.remove(dep); 69 | if (newDeps.isEmpty()) { 70 | // special case for singleton dependency 71 | freed.add(affectedKey); 72 | } else { 73 | depsList.add(newDeps); 74 | } 75 | } 76 | }); 77 | } 78 | return freed; 79 | } 80 | 81 | static class Builder { 82 | private final Map> deps; 83 | 84 | private Builder() { 85 | this.deps = new HashMap<>(); 86 | } 87 | 88 | Builder addDependencies(K key, Set deps) { 89 | this.deps.computeIfAbsent(key, (k) -> new HashSet<>()).addAll(deps); 90 | return this; 91 | } 92 | 93 | DependencyMap build() { 94 | return new DependencyMap<>(this.deps); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/StateMachineBuilderImpl.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import java.util.Collections; 4 | import java.util.EnumSet; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.Objects; 11 | import java.util.Set; 12 | 13 | public class StateMachineBuilderImpl> implements StateMachineBuilder { 14 | 15 | private final Set allStates; 16 | 17 | private final Map>> stateDepsMap; // state to its dependencies 18 | private final Map, List>> stateListenersMap; // dependencies to their triggers 19 | 20 | StateMachineBuilderImpl(Set allStates) { 21 | this(allStates, new HashMap<>(), new HashMap<>()); 22 | } 23 | 24 | StateMachineBuilderImpl(Set allStates, Map>> stateDepsMap, Map, List>> stateListenersMap) { 25 | this.allStates = allStates; 26 | this.stateDepsMap = stateDepsMap; 27 | this.stateListenersMap = stateListenersMap; 28 | } 29 | 30 | static > StateMachineBuilderImpl statesFrom(Class clazz) { 31 | Objects.requireNonNull(clazz); 32 | return new StateMachineBuilderImpl<>(EnumSet.allOf(clazz)); 33 | } 34 | 35 | static > StateMachineBuilderImpl from(StateMachine stateMachine) { 36 | Objects.requireNonNull(stateMachine); 37 | StateMachineImpl stateMachineImpl = (StateMachineImpl) stateMachine; 38 | return new StateMachineBuilderImpl<>(stateMachineImpl._allStates, stateMachineImpl._stateDepsMap, stateMachineImpl._listenerMap); 39 | } 40 | 41 | /* 42 | * transitions related operations 43 | * */ 44 | 45 | @Override 46 | public StateMachineBuilder addTransition(S fromState, S toState) { 47 | return this.addTransition(Collections.singleton(fromState), toState); 48 | } 49 | 50 | @Override 51 | public StateMachineBuilder addTransition(Set requiredStates, S toState) { 52 | Objects.requireNonNull(requiredStates); 53 | Objects.requireNonNull(toState); 54 | if (!requiredStates.isEmpty()) { 55 | this.stateDepsMap.putIfAbsent(toState, new LinkedList<>()); 56 | this.stateDepsMap.get(toState).add(Collections.unmodifiableSet(new HashSet<>(requiredStates))); 57 | } 58 | return this; 59 | } 60 | 61 | @Override 62 | public StateMachineBuilder removeTransition(S fromState, S toState) { 63 | return this.removeTransition(Collections.singleton(fromState), toState); 64 | } 65 | 66 | @Override 67 | public StateMachineBuilder removeTransition(Set requiredStates, S toState) { 68 | if (this.stateDepsMap.containsKey(toState)) { 69 | this.stateDepsMap.get(toState).remove(requiredStates); 70 | } 71 | return this; 72 | } 73 | 74 | /* 75 | * listeners related operations 76 | * */ 77 | 78 | @Override 79 | public StateMachineBuilder addListener(S requiredState, StateListener listener) { 80 | return this.addListener(Collections.singleton(requiredState), listener); 81 | } 82 | 83 | @Override 84 | public StateMachineBuilder addListener(Set requiredStates, StateListener listener) { 85 | Set immutableSets = Collections.unmodifiableSet(new HashSet<>(requiredStates)); 86 | this.stateListenersMap.putIfAbsent(immutableSets, new LinkedList<>()); 87 | this.stateListenersMap.get(immutableSets).add(listener); 88 | return this; 89 | } 90 | 91 | @Override 92 | public StateMachineBuilder addListener(StateListener listener) { 93 | this.allStates.forEach(state -> this.addListener(state, listener)); 94 | return this; 95 | } 96 | 97 | @Override 98 | public StateMachineBuilder removeListener(Set requiredStates, StateListener listener) { 99 | Objects.requireNonNull(requiredStates); 100 | if (this.stateListenersMap.containsKey(requiredStates)) { 101 | this.stateListenersMap.get(requiredStates).remove(listener); 102 | } 103 | return this; 104 | } 105 | 106 | @Override 107 | public StateMachineBuilder removeAllListeners(Set requiredStates) { 108 | Objects.requireNonNull(requiredStates); 109 | this.stateListenersMap.remove(requiredStates); 110 | return this; 111 | } 112 | 113 | @Override 114 | public StateMachine build() { 115 | return new StateMachineImpl<>(stateDepsMap, stateListenersMap, allStates); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /tsm4j/src/main/java/com/tsm4j/core/StateMachineImpl.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Set; 10 | 11 | public class StateMachineImpl> implements StateMachine { 12 | 13 | private final DependencyQueue, S> stateQueue; 14 | private final DependencyQueue>>, S> listenerQueue; 15 | private final StateMachineContextImpl context; 16 | 17 | /* 18 | * Below keeps inputs for toBuilder method only 19 | * */ 20 | final Map>> _stateDepsMap; 21 | final Map, List>> _listenerMap; 22 | final Set _allStates; 23 | 24 | StateMachineImpl(Map>> stateDepsMap, Map, List>> listenerMap, Set allStates) { 25 | this.stateQueue = createStateQueue(stateDepsMap); 26 | this.listenerQueue = new DependencyQueue<>(reverseMapping(listenerMap)); 27 | this.context = new StateMachineContextImpl<>(allStates); 28 | 29 | // create an immutable copy for converting to builder 30 | this._stateDepsMap = new HashMap<>(stateDepsMap); 31 | this._listenerMap = new HashMap<>(listenerMap); 32 | this._allStates = new HashSet<>(allStates); 33 | } 34 | 35 | private static > DependencyQueue, S> createStateQueue(Map>> stateDepsMap) { 36 | Map, Set> newStateDeps = new HashMap<>(); 37 | // each state can be reached from multiple different set of dependencies 38 | // but DependencyMap is for modelling a key mapping to a single set of dependency only 39 | // so we create different keyContainers with the same underlying key (but different hash) 40 | // to stimulate the behaviour of one key having multiple set of dependencies 41 | for (Map.Entry>> depEntry : stateDepsMap.entrySet()) { 42 | S dependent = depEntry.getKey(); 43 | for (Set deps : depEntry.getValue()) { 44 | ObjectContainer keyContainer = new ObjectContainer<>(dependent); 45 | newStateDeps.put(keyContainer, deps); 46 | } 47 | } 48 | return new DependencyQueue<>(newStateDeps); 49 | } 50 | 51 | private static Map>, K> reverseMapping(Map> kvMap) { 52 | Map>> listKeyMap = new HashMap<>(); 53 | kvMap.forEach((k, v) -> listKeyMap.put(k, new ObjectContainer<>(v))); 54 | 55 | Map>, K> reverseMap = new HashMap<>(); 56 | listKeyMap.forEach((k, v) -> reverseMap.put(v, k)); 57 | return reverseMap; 58 | } 59 | 60 | public StateMachineContext send(List states) { 61 | this.queue(states); 62 | return this.process(); 63 | } 64 | 65 | @Override 66 | public StateMachineContext send(S state) { 67 | return send(Collections.singletonList(state)); 68 | } 69 | 70 | @Override 71 | public void queue(List states) { 72 | states.forEach(this::onStateReached); 73 | } 74 | 75 | @Override 76 | public StateMachineContext process() { 77 | // while there is more state reached 78 | while (!this.stateQueue.isEmpty()) { 79 | // get the next reached state 80 | S state = this.stateQueue.pop().get(); 81 | // notify state reached 82 | this.onStateReached(state); 83 | } 84 | return this.context; 85 | } 86 | 87 | @Override 88 | public Set getAllStates() { 89 | return this._allStates; 90 | } 91 | 92 | @Override 93 | public StateMachineBuilder toBuilder() { 94 | return StateMachineBuilderImpl.from(this); 95 | } 96 | 97 | @Override 98 | public boolean reached(S state) { 99 | return this.context.reached(state); 100 | } 101 | 102 | @Override 103 | public int getReachedCount(S state) { 104 | return this.context.getReachedCount(state); 105 | } 106 | 107 | private void onStateReached(S state) { 108 | // mark state satisfied 109 | this.stateQueue.satisfy(state); 110 | // notify context 111 | this.context.onStateReached(state); 112 | // call listeners 113 | this.listenerQueue.satisfy(state); 114 | while (!this.listenerQueue.isEmpty()) { 115 | this.listenerQueue.pop().get().forEach(listener -> listener.accept(this.context)); 116 | } 117 | // consume any state queued by the user 118 | this.context.consumeQueuedStates(this::onStateReached); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /tsm4j/src/test/java/com/tsm4j/core/DependencyMapTest.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.Arrays; 6 | import java.util.HashSet; 7 | import java.util.Set; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | 11 | class DependencyMapTest { 12 | 13 | @Test 14 | void orderedSatisfy() { 15 | DependencyMap mapUnderTest = DependencyMap.builder() 16 | .addDependencies("1", setOf(1)) 17 | .addDependencies("1-3", setOf(1, 2, 3)) 18 | .addDependencies("1-5", setOf(1, 2, 3, 4, 5)) 19 | .build(); 20 | 21 | assertThat(mapUnderTest.satisfy(1)).containsExactly("1"); 22 | assertThat(mapUnderTest.satisfy(2)).isEmpty(); 23 | assertThat(mapUnderTest.satisfy(3)).containsExactly("1-3"); 24 | assertThat(mapUnderTest.satisfy(4)).isEmpty(); 25 | assertThat(mapUnderTest.satisfy(5)).containsExactly("1-5"); 26 | } 27 | 28 | @Test 29 | void multipleSameValue() { 30 | DependencyMap mapUnderTest = DependencyMap.builder() 31 | .addDependencies("1", setOf(1)) 32 | .build(); 33 | 34 | assertThat(mapUnderTest.satisfy(1)).containsExactly("1"); 35 | assertThat(mapUnderTest.satisfy(1)).containsExactly("1"); 36 | assertThat(mapUnderTest.satisfy(1)).containsExactly("1"); 37 | } 38 | 39 | @Test 40 | void sameDependencies() { 41 | DependencyMap mapUnderTest = DependencyMap.builder() 42 | .addDependencies("a", setOf(1, 2)) 43 | .addDependencies("b", setOf(1, 2)) 44 | .build(); 45 | 46 | assertThat(mapUnderTest.satisfy(1)).isEmpty(); 47 | assertThat(mapUnderTest.satisfy(2)).containsExactlyInAnyOrder("a", "b"); 48 | } 49 | 50 | @Test 51 | void multipleSameDependencies() { 52 | DependencyMap mapUnderTest = DependencyMap.builder() 53 | .addDependencies("a1-3", setOf(1, 2, 3)) 54 | .addDependencies("b1-3", setOf(1, 2, 3)) 55 | .addDependencies("a2-4", setOf(2, 3, 4)) 56 | .addDependencies("b2-4", setOf(2, 3, 4)) 57 | .addDependencies("a3-5", setOf(3, 4, 5)) 58 | .addDependencies("b3-5", setOf(3, 4, 5)) 59 | .build(); 60 | 61 | assertThat(mapUnderTest.satisfy(1)).isEmpty(); 62 | assertThat(mapUnderTest.satisfy(2)).isEmpty(); 63 | assertThat(mapUnderTest.satisfy(3)).containsExactlyInAnyOrder("a1-3", "b1-3"); 64 | assertThat(mapUnderTest.satisfy(4)).containsExactlyInAnyOrder("a2-4", "b2-4"); 65 | assertThat(mapUnderTest.satisfy(5)).containsExactlyInAnyOrder("a3-5", "b3-5"); 66 | } 67 | 68 | @Test 69 | void multipleSameDependencies2() { 70 | DependencyMap mapUnderTest = DependencyMap.builder() 71 | .addDependencies("a1-3", setOf(1, 2, 3)) 72 | .addDependencies("b1-3", setOf(1, 2, 3)) 73 | .addDependencies("c1-3", setOf(1, 2, 3)) 74 | .addDependencies("a3-5", setOf(3, 4, 5)) 75 | .addDependencies("b3-5", setOf(3, 4, 5)) 76 | .addDependencies("c3-5", setOf(3, 4, 5)) 77 | .build(); 78 | 79 | assertThat(mapUnderTest.satisfy(1)).isEmpty(); 80 | assertThat(mapUnderTest.satisfy(2)).isEmpty(); 81 | assertThat(mapUnderTest.satisfy(3)).containsExactlyInAnyOrder("a1-3", "b1-3", "c1-3"); 82 | assertThat(mapUnderTest.satisfy(4)).isEmpty(); 83 | assertThat(mapUnderTest.satisfy(5)).containsExactlyInAnyOrder("a3-5", "b3-5", "c3-5"); 84 | } 85 | 86 | @Test 87 | void unevenSatisfyOrder() { 88 | DependencyMap mapUnderTest = DependencyMap.builder() 89 | .addDependencies("1-3", setOf(1, 2, 3)) 90 | .build(); 91 | 92 | assertThat(mapUnderTest.satisfy(1)).isEmpty(); 93 | assertThat(mapUnderTest.satisfy(1)).isEmpty(); 94 | assertThat(mapUnderTest.satisfy(1)).isEmpty(); 95 | assertThat(mapUnderTest.satisfy(2)).isEmpty(); 96 | assertThat(mapUnderTest.satisfy(2)).isEmpty(); 97 | assertThat(mapUnderTest.satisfy(3)).containsExactly("1-3"); 98 | assertThat(mapUnderTest.satisfy(3)).containsExactly("1-3"); 99 | assertThat(mapUnderTest.satisfy(3)).isEmpty(); 100 | assertThat(mapUnderTest.satisfy(2)).containsExactly("1-3"); 101 | } 102 | 103 | @Test 104 | void overlappingDependencies() { 105 | DependencyMap mapUnderTest = DependencyMap.builder() 106 | .addDependencies("1-3", setOf(1, 2, 3)) 107 | .addDependencies("2-4", setOf(2, 3, 4)) 108 | .addDependencies("3-5", setOf(3, 4, 5)) 109 | .build(); 110 | 111 | assertThat(mapUnderTest.satisfy(1)).isEmpty(); 112 | assertThat(mapUnderTest.satisfy(2)).isEmpty(); 113 | assertThat(mapUnderTest.satisfy(3)).containsExactly("1-3"); 114 | assertThat(mapUnderTest.satisfy(4)).containsExactly("2-4"); 115 | assertThat(mapUnderTest.satisfy(5)).containsExactly("3-5"); 116 | } 117 | 118 | @Test 119 | void addingDependenciesOfSameKey() { 120 | DependencyMap mapUnderTest = DependencyMap.builder() 121 | .addDependencies("1-3", setOf(1)) 122 | .addDependencies("1-3", setOf(2)) 123 | .addDependencies("1-3", setOf(3)) 124 | .build(); 125 | 126 | assertThat(mapUnderTest.satisfy(1)).isEmpty(); 127 | assertThat(mapUnderTest.satisfy(2)).isEmpty(); 128 | assertThat(mapUnderTest.satisfy(3)).containsExactly("1-3"); 129 | } 130 | 131 | @SafeVarargs 132 | private final Set setOf(T... values) { 133 | return new HashSet<>(Arrays.asList(values)); 134 | } 135 | } -------------------------------------------------------------------------------- /tsm4j/src/test/java/com/tsm4j/core/StateMachineTest.java: -------------------------------------------------------------------------------- 1 | package com.tsm4j.core; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.Arrays; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Set; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | 12 | class StateMachineTest { 13 | 14 | private static StateListener debugLoggingListener() { 15 | return context -> System.out.printf("[STATE]: %s%n", context.getLatestState()); 16 | } 17 | 18 | @Test 19 | public void serialTransition() { 20 | StateMachine stateMachine = StateMachineBuilder.from(TestState.class) 21 | .addTransition(TestState.HUNGRY, TestState.MAKE_FOOD) 22 | .addTransition(TestState.MAKE_FOOD, TestState.FOOD_IS_READY) 23 | .addTransition(TestState.FOOD_IS_READY, TestState.EAT_FOOD) 24 | .addTransition(TestState.EAT_FOOD, TestState.FULL) 25 | .addListener(debugLoggingListener()) 26 | .build(); 27 | 28 | assertThat(stateMachine.send(TestState.HUNGRY).reached(TestState.FULL)).isTrue(); 29 | } 30 | 31 | @Test 32 | public void compoundTransition1() { 33 | StateMachine stateMachine = StateMachineBuilder.from(TestState.class) 34 | .addTransition(setOf(TestState.HUNGRY, TestState.NO_FOOD), TestState.MAKE_FOOD) 35 | .addTransition(TestState.MAKE_FOOD, TestState.FOOD_IS_READY) 36 | .addTransition(setOf(TestState.HUNGRY, TestState.FOOD_IS_READY), TestState.EAT_FOOD) 37 | .addTransition(TestState.EAT_FOOD, TestState.FULL) 38 | .addListener(debugLoggingListener()) 39 | .build(); 40 | 41 | assertThat(stateMachine.send(listOf(TestState.HUNGRY, TestState.NO_FOOD)).reached(TestState.FULL)).isTrue(); 42 | } 43 | 44 | @Test 45 | public void compoundTransition2() { 46 | StateMachine stateMachine = StateMachineBuilder.from(TestState.class) 47 | .addTransition(setOf(TestState.HUNGRY, TestState.NO_FOOD), TestState.MAKE_FOOD) 48 | .addTransition(TestState.MAKE_FOOD, TestState.FOOD_IS_READY) 49 | .addTransition(setOf(TestState.HUNGRY, TestState.FOOD_IS_READY), TestState.EAT_FOOD) 50 | .addTransition(TestState.EAT_FOOD, TestState.FULL) 51 | .addListener(debugLoggingListener()) 52 | .build(); 53 | 54 | assertThat(stateMachine.send(TestState.HUNGRY).reached(TestState.FULL)).isFalse(); 55 | assertThat(stateMachine.send(TestState.NO_FOOD).reached(TestState.FULL)).isTrue(); 56 | } 57 | 58 | @Test 59 | public void queueWithContext1() { 60 | StateMachine stateMachine = StateMachineBuilder.from(TestState.class) 61 | .addTransition(TestState.NO_FOOD, TestState.MAKE_FOOD) 62 | .addTransition(TestState.MAKE_FOOD, TestState.FOOD_IS_READY) 63 | 64 | .addTransition(setOf(TestState.HUNGRY, TestState.FOOD_IS_READY), TestState.EAT_FOOD) 65 | .addTransition(TestState.EAT_FOOD, TestState.FULL) 66 | 67 | .addListener(TestState.FOOD_IS_READY, context -> context.queue(TestState.HUNGRY)) 68 | 69 | .addListener(debugLoggingListener()) 70 | .build(); 71 | 72 | assertThat(stateMachine.send(TestState.NO_FOOD).reached(TestState.FULL)).isTrue(); 73 | } 74 | 75 | @Test 76 | public void queueWithContext2() { 77 | StateMachine stateMachine = StateMachineBuilder.from(TestState.class) 78 | .addTransition(TestState.NO_FOOD, TestState.MAKE_FOOD) 79 | .addListener(TestState.MAKE_FOOD, context -> { 80 | System.out.println("making food..."); 81 | context.queue(TestState.FOOD_IS_READY); 82 | }) 83 | .addListener(debugLoggingListener()) 84 | .build(); 85 | 86 | assertThat(stateMachine.send(TestState.NO_FOOD).reached(TestState.FOOD_IS_READY)).isTrue(); 87 | } 88 | 89 | @SafeVarargs 90 | private final Set setOf(T... values) { 91 | return new HashSet<>(Arrays.asList(values)); 92 | } 93 | 94 | // @Test 95 | // public void testHandleException() { 96 | // StateMachine stateMachine = StateMachineBuilder.newInstance() 97 | // .addTransition(MyState.HUNGRY, context -> { 98 | // throw new RuntimeException("exception!"); 99 | // }) 100 | // .addExceptionHandler(RuntimeException.class, (context, e) -> { 101 | // // custom eat food logic 102 | // context.send(MyState.NOT_HUNGRY); 103 | // }) 104 | // .build(); 105 | // 106 | // assertTrue(stateMachine.send(MyState.HUNGRY).hasReached(MyState.NOT_HUNGRY)); 107 | // } 108 | // 109 | // @Test 110 | // public void testHandleNestedException() { 111 | // StateMachine stateMachine = StateMachineBuilder.newInstance() 112 | // .addTransition(MyState.HUNGRY, context -> { 113 | // throw new RuntimeException("exception!"); 114 | // }) 115 | // .addExceptionHandler(RuntimeException.class, (context, e) -> { 116 | // throw new IllegalStateException("nested exception!"); 117 | // }) 118 | // .addExceptionHandler(IllegalStateException.class, (context, e) -> { 119 | // context.send(MyState.NOT_HUNGRY); 120 | // }) 121 | // .build(); 122 | // 123 | // assertTrue(stateMachine.send(MyState.HUNGRY).hasReached(MyState.NOT_HUNGRY)); 124 | // } 125 | // 126 | // @Test 127 | // public void testHandleSubclassException() { 128 | // StateMachine stateMachine = StateMachineBuilder.newInstance() 129 | // .addTransition(MyState.HUNGRY, context -> { 130 | // throw new IllegalStateException("nested exception!"); 131 | // }) 132 | // .addExceptionHandler(RuntimeException.class, (context, e) -> { 133 | // context.send(MyState.NOT_HUNGRY); 134 | // }) 135 | // .build(); 136 | // 137 | // assertTrue(stateMachine.send(MyState.HUNGRY).hasReached(MyState.NOT_HUNGRY)); 138 | // } 139 | // 140 | // @Test 141 | // public void testHandleThrowingSameException() { 142 | // StateMachine stateMachine = StateMachineBuilder.newInstance() 143 | // .addTransition(MyState.HUNGRY, context -> { 144 | // throw new RuntimeException("exception!"); 145 | // }) 146 | // .addExceptionHandler(RuntimeException.class, (context, e) -> { 147 | // throw e; 148 | // }) 149 | // .build(); 150 | // 151 | // assertThatThrownBy(() -> stateMachine.send(MyState.HUNGRY)) 152 | // .isInstanceOf(RuntimeException.class) 153 | // .hasMessage("exception!"); 154 | // } 155 | // 156 | // @Test 157 | // public void testThrowingNotHandledException() { 158 | // StateMachine stateMachine = StateMachineBuilder.newInstance() 159 | // .addTransition(MyState.HUNGRY, context -> { 160 | // throw new RuntimeException("exception!"); 161 | // }) 162 | // .build(); 163 | // 164 | // assertThatThrownBy(() -> stateMachine.send(MyState.HUNGRY)) 165 | // .isInstanceOf(RuntimeException.class) 166 | // .hasMessage("exception!"); 167 | // } 168 | 169 | @SafeVarargs 170 | private final List listOf(T... values) { 171 | return Arrays.asList(values); 172 | } 173 | 174 | private enum TestState { 175 | HUNGRY, 176 | NO_FOOD, 177 | FOOD_IS_NOT_READY, 178 | MAKE_FOOD, 179 | FOOD_IS_READY, 180 | NOT_HUNGRY, 181 | ATTEMPTS, 182 | EAT_FOOD, 183 | FULL, 184 | } 185 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | # Collect all arguments for the java command; 201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 202 | # shell script including quotes and variable substitutions, so put them in 203 | # double quotes to make sure that they get re-expanded; and 204 | # * put everything else in single quotes, so that it's not re-expanded. 205 | 206 | set -- \ 207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 208 | -classpath "$CLASSPATH" \ 209 | org.gradle.wrapper.GradleWrapperMain \ 210 | "$@" 211 | 212 | # Stop when "xargs" is not available. 213 | if ! command -v xargs >/dev/null 2>&1 214 | then 215 | die "xargs is not available" 216 | fi 217 | 218 | # Use "xargs" to parse quoted args. 219 | # 220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 221 | # 222 | # In Bash we could simply go: 223 | # 224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 225 | # set -- "${ARGS[@]}" "$@" 226 | # 227 | # but POSIX shell has neither arrays nor command substitution, so instead we 228 | # post-process each arg (as a line of input to sed) to backslash-escape any 229 | # character that might be a shell metacharacter, then use eval to reverse 230 | # that process (while maintaining the separation between arguments), and wrap 231 | # the whole thing up as a single "set" statement. 232 | # 233 | # This will of course break if any of these variables contains a newline or 234 | # an unmatched quote. 235 | # 236 | 237 | eval "set -- $( 238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 239 | xargs -n1 | 240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 241 | tr '\n' ' ' 242 | )" '"$@"' 243 | 244 | exec "$JAVACMD" "$@" 245 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------