├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE.txt
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
└── java
│ └── de
│ └── muspellheim
│ └── eventbus
│ ├── EventBus.java
│ └── package-info.java
└── test
└── java
└── de
└── muspellheim
└── eventbus
├── EventBusExample.java
└── EventBusTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # Gradle
2 | build/
3 | .gradle
4 | gradle.properties
5 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - oraclejdk8
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Changelog
2 | =========
3 |
4 | All notable changes to this project will be documented in this file.
5 |
6 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
7 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
8 |
9 | ## [Unreleased]
10 |
11 | ## [1.1.0] - 2017-08-03
12 |
13 | ### Added
14 |
15 | * Library is an OSGi bundle and Eclipse plug-in also.
16 |
17 | ## 1.0.0 - 2017-07-29
18 |
19 | ### Added
20 |
21 | * Event bus to subribe and publish events.
22 |
23 |
24 | [Unreleased]: https://github.com/falkoschumann/java-eventbus/compare/v1.1.0...HEAD
25 | [1.1.0]: https://github.com/falkoschumann/java-eventbus/compare/v1.0.0...v1.1.0
26 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Falko Schumann
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://travis-ci.org/falkoschumann/java-eventbus)
2 | []()
3 |
4 |
5 | Eventbus
6 | ========
7 |
8 | Subscribe and publish events. Events are published in channels distinguished by
9 | event type. Channels can be grouped using an event type hierarchy.
10 |
11 | You can use the default event bus instance, which is a singleton or you can
12 | create one or multiple instances.
13 |
14 |
15 | Installation
16 | ------------
17 |
18 | ### Gradle
19 |
20 | Add the the repository _jcenter_ to your `build.gradle`
21 |
22 | repositories {
23 | jcenter()
24 | }
25 |
26 | and add the dependency
27 |
28 | compile 'de.muspellheim:eventbus:1.1.0'
29 |
30 |
31 | ### Maven
32 |
33 | Add the the repository _jcenter_ to your `pom.xml`
34 |
35 |
36 |
37 |
38 | false
39 |
40 | central
41 | bintray
42 | http://jcenter.bintray.com
43 |
44 |
45 |
46 | and add the dependency
47 |
48 |
49 |
50 | de.muspellheim
51 | eventbus
52 | 1.1.0
53 |
54 |
55 |
56 |
57 | ### Download
58 |
59 | You can download JARs with binary, source and JavaDoc from GitHub under
60 | https://github.com/falkoschumann/java-eventbus/releases.
61 |
62 |
63 | Usage
64 | -----
65 |
66 | You can create an individual event bus by constructor or use the default event
67 | bus as singleton.
68 |
69 | EventBus bus = EventBus.getDefault();
70 |
71 | Subscribe to an event by type. You can use every class as event type.
72 | Subscribing a super type works as subcribe to any sub type.
73 |
74 | bus.subscribe(String.class, s -> System.out.println("String: " + s));
75 | bus.subscribe(Number.class, n -> System.out.println("Number: " + n));
76 |
77 | Let's publish some events.
78 |
79 | bus.publish("Foo"); // String
80 | bus.publish(42); // int
81 | bus.publish(2.718); // double
82 |
83 | The example output:
84 |
85 | String: Foo
86 | Number: 42
87 | Number: 2.718
88 |
89 |
90 | Contributing
91 | ------------
92 |
93 | ### Publish artifacts to Bintray
94 |
95 | 1. Create file `gradle.properties` and set properties `bintrayUser` and
96 | `bintrayApiKey`.
97 | 2. Run `./gradlew uploadArchives`.
98 | 3. Check uploaded files and publish.
99 |
100 | ### Publish distribution to GitHub
101 |
102 | 1. Run `./gradle distZip`.
103 | 2. Upload created ZIP to GitHub releases.
104 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | mavenCentral()
4 | }
5 | dependencies {
6 | classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:3.4.0'
7 | }
8 | }
9 |
10 | apply plugin: 'findbugs'
11 | apply plugin: 'java'
12 | apply plugin: 'maven'
13 | apply plugin: 'biz.aQute.bnd.builder'
14 |
15 | group = 'de.muspellheim'
16 | version = '1.1.0'
17 |
18 | sourceCompatibility = 1.8
19 | compileJava.options.encoding = 'UTF-8'
20 |
21 | repositories {
22 | jcenter()
23 | }
24 |
25 | dependencies {
26 | testImplementation 'junit:junit:4.12'
27 | }
28 |
29 | jar {
30 | manifest {
31 | attributes('Bundle-Name': project.name[0].toUpperCase() + project.name.substring(1))
32 | attributes('Bundle-SymbolicName': project.group + '.' + project.name)
33 | attributes('Export-Package': project.group + '.' + project.name + '.*', '-sources': 'true',)
34 | }
35 | }
36 |
37 | task sourcesJar(type: Jar, dependsOn: classes) {
38 | classifier = 'sources'
39 | from sourceSets.main.allSource
40 | }
41 |
42 | task javadocJar(type: Jar, dependsOn: javadoc) {
43 | classifier = 'javadoc'
44 | from javadoc.destinationDir
45 | }
46 |
47 | artifacts {
48 | archives sourcesJar
49 | archives javadocJar
50 | }
51 |
52 | def bintrayUser = project.hasProperty('bintrayUser') ? project.property('bintrayUser') : System.getenv('BINTRAY_USER')
53 | def bintrayApiKey = project.hasProperty('bintrayApiKey') ? project.property('bintrayApiKey') : System.getenv('BINTRAY_API_KEY')
54 | uploadArchives {
55 | repositories {
56 | mavenDeployer {
57 | repository(url: "https://api.bintray.com/maven/falkoschumann/maven/${project.name}/;publish=0") {
58 | authentication(userName: bintrayUser, password: bintrayApiKey)
59 | }
60 | }
61 | }
62 | }
63 |
64 | task distZip(type: Zip) {
65 | from 'src/dist'
66 | from jar.outputs.files
67 | from sourcesJar.outputs.files
68 | from javadocJar.outputs.files
69 | from(projectDir) {
70 | include('README.md', 'CHANGELOG.md', 'LICENSE.txt')
71 | rename { fileName -> fileName.replace('.md', '.txt') }
72 | }
73 | }
74 |
75 | tasks.withType(FindBugs) {
76 | reports {
77 | xml.enabled false
78 | html.enabled true
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/falkoschumann/java-eventbus/d64cce8c1ce0149d86328d715a87a419714081a0/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue May 09 18:23:54 CEST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn ( ) {
37 | echo "$*"
38 | }
39 |
40 | die ( ) {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save ( ) {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'eventbus'
2 |
--------------------------------------------------------------------------------
/src/main/java/de/muspellheim/eventbus/EventBus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Falko Schumann
3 | * Released under the terms of the MIT License.
4 | */
5 |
6 | package de.muspellheim.eventbus;
7 |
8 | import java.util.*;
9 | import java.util.concurrent.*;
10 | import java.util.function.*;
11 |
12 | /**
13 | * Simple event bus implementation.
14 | *
15 | * Subscribe and publish events. Events are published in channels distinguished by event type. Channels can be grouped
16 | * using an event type hierarchy.
17 | *
18 | * You can use the default event bus instance {@link #getDefault}, which is a singleton or you can create one or multiple
19 | * instances of {@link EventBus}.
20 | */
21 | public class EventBus {
22 |
23 | private static EventBus INSTANCE = new EventBus();
24 |
25 | private final Map, Set> subscribers = new ConcurrentHashMap<>();
26 |
27 | /**
28 | * Get the default event bus, can be used as application wide singleton.
29 | *
30 | * @return the only instance of the default event bus.
31 | */
32 | public static EventBus getDefault() {
33 | return INSTANCE;
34 | }
35 |
36 | /**
37 | * Subscribe to an event type
38 | *
39 | * @param eventType the event type, can be a super class of all events to subscribe.
40 | * @param subscriber the subscriber which will consume the events.
41 | * @param the event type class.
42 | */
43 | public void subscribe(Class extends T> eventType, Consumer subscriber) {
44 | Objects.requireNonNull(eventType, "eventType");
45 | Objects.requireNonNull(subscriber, "subscriber");
46 |
47 | Set eventSubscribers = getOrCreateSubscribers(eventType);
48 | eventSubscribers.add(subscriber);
49 | }
50 |
51 | private Set getOrCreateSubscribers(Class eventType) {
52 | Set eventSubscribers = subscribers.get(eventType);
53 | if (eventSubscribers == null) {
54 | eventSubscribers = new CopyOnWriteArraySet<>();
55 | subscribers.put(eventType, eventSubscribers);
56 | }
57 | return eventSubscribers;
58 | }
59 |
60 | /**
61 | * Unsubscribe from all event types.
62 | *
63 | * @param subscriber the subscriber to unsubscribe.
64 | */
65 | public void unsubscribe(Consumer> subscriber) {
66 | Objects.requireNonNull(subscriber, "subscriber");
67 |
68 | subscribers.values().forEach(eventSubscribers -> eventSubscribers.remove(subscriber));
69 | }
70 |
71 | /**
72 | * Unsubscribe from an event type.
73 | *
74 | * @param eventType the event type, can be a super class of all events to unsubscribe.
75 | * @param subscriber the subscriber to unsubscribe.
76 | * @param the event type class.
77 | */
78 | public void unsubscribe(Class extends T> eventType, Consumer subscriber) {
79 | Objects.requireNonNull(eventType, "eventType");
80 | Objects.requireNonNull(subscriber, "subscriber");
81 |
82 | subscribers.keySet().stream()
83 | .filter(type -> eventType.isAssignableFrom(type))
84 | .map(type -> subscribers.get(type))
85 | .forEach(eventSubscribers -> eventSubscribers.remove(subscriber));
86 | }
87 |
88 | /**
89 | * Publish an event to all subscribers.
90 | *
91 | * The event type is the class of event
. The event is published to all consumers which subscribed to
92 | * this event type or any super class.
93 | *
94 | * @param event the event.
95 | */
96 | public void publish(Object event) {
97 | Objects.requireNonNull(event, "event");
98 |
99 | Class> eventType = event.getClass();
100 | subscribers.keySet().stream()
101 | .filter(type -> type.isAssignableFrom(eventType))
102 | .flatMap(type -> subscribers.get(type).stream())
103 | .forEach(subscriber -> publish(event, subscriber));
104 | }
105 |
106 | private static void publish(Object event, Consumer subscriber) {
107 | try {
108 | subscriber.accept(event);
109 | } catch (Exception e) {
110 | Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);
111 | }
112 | }
113 |
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/de/muspellheim/eventbus/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Falko Schumann
3 | * Released under the terms of the MIT License.
4 | */
5 |
6 | /**
7 | * Use Eventbus
to subscribe and publish application wide events.
8 | */
9 | package de.muspellheim.eventbus;
10 |
--------------------------------------------------------------------------------
/src/test/java/de/muspellheim/eventbus/EventBusExample.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Falko Schumann
3 | * Released under the terms of the MIT License.
4 | */
5 |
6 | package de.muspellheim.eventbus;
7 |
8 | public class EventBusExample {
9 |
10 | public void usage() {
11 | EventBus bus = EventBus.getDefault();
12 |
13 | bus.subscribe(String.class, s -> System.out.println("String: " + s));
14 | bus.subscribe(Number.class, n -> System.out.println("Number: " + n));
15 |
16 | bus.publish("Foo");
17 | bus.publish(42);
18 | bus.publish(2.718);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/de/muspellheim/eventbus/EventBusTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Falko Schumann
3 | * Released under the terms of the MIT License.
4 | */
5 |
6 | package de.muspellheim.eventbus;
7 |
8 | import org.junit.*;
9 |
10 | import java.util.*;
11 | import java.util.function.*;
12 |
13 | import static org.junit.Assert.*;
14 |
15 | /**
16 | * Unit tests, integration tests, acceptance tests and examples.
17 | *
18 | * Not enough stuff to separate it.
19 | */
20 | public class EventBusTest {
21 |
22 | private List stringEvents = new ArrayList<>();
23 | private List integerEvents = new ArrayList<>();
24 | private List numberEvents = new ArrayList<>();
25 | private List doubleEvents = new ArrayList<>();
26 |
27 | private void consumeString(String event) {
28 | stringEvents.add(event);
29 | }
30 |
31 | private void consumeInt(int event) {
32 | integerEvents.add(event);
33 | }
34 |
35 | private void consumeNumber(Number event) {
36 | numberEvents.add(event);
37 | }
38 |
39 | private void consumeDouble(Number event) {
40 | doubleEvents.add(event);
41 | }
42 |
43 | @Test(expected = NullPointerException.class)
44 | public void subscribe_EventTypeNull() {
45 | EventBus bus = EventBus.getDefault();
46 | bus.subscribe(null, this::consumeString);
47 | }
48 |
49 | @Test(expected = NullPointerException.class)
50 | public void subscribe_SubscriberNull() {
51 | EventBus bus = EventBus.getDefault();
52 | bus.subscribe(String.class, null);
53 | }
54 |
55 | @Test(expected = NullPointerException.class)
56 | public void unsubscribe_EventTypeNull() {
57 | EventBus bus = EventBus.getDefault();
58 | bus.unsubscribe(null, this::consumeString);
59 | }
60 |
61 | @Test(expected = NullPointerException.class)
62 | public void unsubscribe_SubscriberNull() {
63 | EventBus bus = EventBus.getDefault();
64 | bus.unsubscribe(null);
65 | }
66 |
67 | @Test(expected = NullPointerException.class)
68 | public void publish_EventNull() {
69 | EventBus bus = EventBus.getDefault();
70 |
71 | bus.publish(null);
72 | }
73 |
74 | @Test
75 | public void publish() {
76 | EventBus bus = EventBus.getDefault();
77 | bus.subscribe(String.class, this::consumeString);
78 | bus.subscribe(Integer.class, this::consumeInt);
79 |
80 | bus.publish("Foo");
81 | bus.publish(42);
82 | bus.publish("Bar");
83 |
84 | assertEquals("string events", Arrays.asList("Foo", "Bar"), stringEvents);
85 | assertEquals("integer events", Arrays.asList(42), integerEvents);
86 | }
87 |
88 | @Test
89 | public void unsubscribe() {
90 | EventBus bus = EventBus.getDefault();
91 | Consumer subscriber = this::consumeString;
92 | bus.subscribe(String.class, subscriber);
93 |
94 | bus.publish("Foo");
95 | bus.unsubscribe(subscriber);
96 | bus.publish("Bar");
97 |
98 | assertEquals(Arrays.asList("Foo"), stringEvents);
99 | }
100 |
101 | @Test
102 | public void eventTypeHierarchy() {
103 | EventBus bus = EventBus.getDefault();
104 | Consumer intSubscriber = this::consumeInt;
105 | bus.subscribe(Integer.class, intSubscriber);
106 | Consumer numberSubscriber = this::consumeNumber;
107 | bus.subscribe(Number.class, numberSubscriber);
108 | Consumer doubleSubscriber = this::consumeDouble;
109 | bus.subscribe(Double.class, doubleSubscriber);
110 |
111 | bus.publish(0.815);
112 | bus.publish(42);
113 | bus.unsubscribe(Number.class, numberSubscriber);
114 | bus.unsubscribe(Number.class, doubleSubscriber);
115 | bus.publish(2.718);
116 | bus.unsubscribe(Integer.class, intSubscriber);
117 | bus.publish(7);
118 |
119 | assertEquals("integer events", Arrays.asList(42), integerEvents);
120 | assertEquals("number events", Arrays.asList(0.815, 42), numberEvents);
121 | assertEquals("double events", Arrays.asList(0.815), doubleEvents);
122 | }
123 |
124 | }
125 |
--------------------------------------------------------------------------------